Injecting dependencies into types that are not components using Windsor

Sometimes I find the need to inject dependencies from the container into a type that is not registered as a component. It does not come up very often, but mainly it is something that I need when writing tests and it does not make sense to register my object with the container.  Turns out this is pretty easy with Windsor:

 

   1: public static class IKernelExtensions
   2: {
   3:  
   4:     public static T Autowire<T>(this IKernel kernel)
   5:     {
   6:         ComponentModel component = kernel.ComponentModelBuilder.BuildModel(typeof(T).FullName, typeof(T), typeof(T), null);
   7:         var activator = kernel.CreateComponentActivator(component);
   8:         return (T)activator.Create(CreationContext.Empty);
   9:     }
  10:  
  11: }
  12:  
  13: [TestClass]
  14: public class IKernelExtensionsTests 
  15: {
  16:     [TestMethod, ExpectedException(typeof(ComponentNotFoundException)]
  17:     public void Autowire_creates_an_object_with_adding_to_container()
  18:     {
  19:         var kernel = new DefaultKernel();
  20:         kernel.AddComponent("test", typeof(IServiceInterface), typeof(ServiceInferface));
  21:         var someService = kernel.Autowire<SomeService>();
  22:         Assert.IsNotNull(someService.ServiceInterface);
  23:         kernel.Resolve<SomeService>();
  24:         Assert.Fail();
  25:     }
  26:  
  27:     [TestMethod, ExpectedException(typeof(ComponentNotFoundException))]
  28:     public void Autowire_creates_an_object_with_adding_to_container_using_constructur()
  29:     {
  30:         var kernel = new DefaultKernel();
  31:         kernel.AddComponent("test", typeof(IServiceInterface), typeof(ServiceInferface));
  32:         var someService = kernel.Autowire<SomeServiceCtorInjection>();
  33:         Assert.IsNotNull(someService.ServiceInterface);
  34:         kernel.Resolve<SomeServiceCtorInjection>();
  35:         Assert.Fail();
  36:     }
  37:  
  38:     public class SomeService
  39:     {
  40:         public IServiceInterface ServiceInterface { get; set; }
  41:     }
  42:  
  43:     public class SomeServiceCtorInjection
  44:     {
  45:         public SomeServiceCtorInjection(IServiceInterface serviceInterface)
  46:         {
  47:             ServiceInterface = serviceInterface;
  48:         }
  49:  
  50:         public IServiceInterface ServiceInterface { get; private set; }
  51:     }
  52:  
  53:     public interface IServiceInterface
  54:     {
  55:     }
  56:  
  57:     public class ServiceInferface : IServiceInterface
  58:     {    
  59:     }
  60: }

One Comment