Created
May 31, 2010 04:14
-
-
Save kkozmic/419518 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Castle.Windsor.Tests | |
{ | |
using System; | |
using System.Collections.Generic; | |
using Castle.Core; | |
using Castle.MicroKernel; | |
using Castle.MicroKernel.ComponentActivator; | |
using Castle.MicroKernel.Registration; | |
using Castle.MicroKernel.Resolvers; | |
using Castle.MicroKernel.Tests.ClassComponents; | |
using NUnit.Framework; | |
[TestFixture] | |
public class InjectIntoExistingInstanceTestCase | |
{ | |
private IWindsorContainer container; | |
[SetUp] | |
public void SetUpTests() | |
{ | |
container = new WindsorContainer(); | |
container.Register(Component.For<ResolveDependenciesOfInstance>()); | |
} | |
[Test] | |
public void CanDecorateExistingInstance() | |
{ | |
container.Register( | |
Component.For<DefaultMailSenderService>(), | |
Component.For<DefaultTemplateEngine>() | |
); | |
var service = new DefaultSpamService(); | |
container.ResolveDependenciesOf(service); | |
Assert.IsNotNull(service.MailSender); | |
Assert.IsNotNull(service.TemplateEngine); | |
Assert.AreSame(container.Resolve<DefaultMailSenderService>(), service.MailSender); | |
Assert.AreSame(container.Resolve<DefaultTemplateEngine>(),service.TemplateEngine); | |
} | |
} | |
public static class ResolveDependenciesOfExtension | |
{ | |
public static void ResolveDependenciesOf(this IWindsorContainer container, object existingInstance) | |
{ | |
var dependency = new Dictionary<string,object>{{"Castle.InstanceToResolveDependenciesOf", existingInstance}}; | |
container.Resolve("DecorateInstance:"+existingInstance.GetType().FullName,existingInstance.GetType(),new Arguments(dependency )); | |
} | |
} | |
public class ResolveDependenciesOfInstance:ILazyComponentLoader | |
{ | |
public IRegistration Load(string key, Type service) | |
{ | |
if(service == null || key == null || key != "DecorateInstance:"+service.FullName) | |
{ | |
return null; | |
} | |
return Component.For(service).Named(key) | |
.Activator<ExistingInstanceActivator>() | |
.LifeStyle.Transient; | |
} | |
} | |
public class ExistingInstanceActivator:DefaultComponentActivator | |
{ | |
public ExistingInstanceActivator(ComponentModel model, IKernel kernel, | |
ComponentInstanceDelegate onCreation, | |
ComponentInstanceDelegate onDestruction) | |
: base(model, kernel, onCreation, onDestruction){} | |
protected override object Instantiate(Castle.MicroKernel.Context.CreationContext context) | |
{ | |
return context.AdditionalParameters["Castle.InstanceToResolveDependenciesOf"]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment