Windsor Castle IoC Property Injection Simple Practical

OK. I think there might be too much information about Castle Windsor, because searching for these keywords gives me examples of everything, and to be honest, I don’t understand how it works to fix this problem correctly. At the moment, I have tried many permutations with little luck.

I have an IUnitOfWorkFactory that I want to create as a singleton. So, I install Castle Windsor, write some code:

 iocContainer = new WindsorContainer() .Install(FromAssembly.This()); var propInjector = iocContainer.Register( Component.For<IUnitOfWorkFactory>() .LifestyleSingleton() .Instance(new NHUnitOfWorkFactory()) ); propInjector.Resolve<IUnitOfWorkFactory>(); 

This is called from my Application_Start method.

I have an AccountController connected like this:

 public class AccountController : SecureController { public IUnitOfWorkFactory UnitOfWorkFactory { get; set; } ... 

... as far as I can understand, this should just “work” (although don't ask me how). But my property is always null when I try to use it.

It seems like I missed something stupid and simple, but I have no idea what it is.

I also tried

 var propInjector = iocContainer.Register( Component.For<IUnitOfWorkFactory>() .ImplementedBy<NHUnitOfWorkFactory>() .LifestyleSingleton() ); 

without success.

What am I doing wrong?

Conclusion

I was missing a few steps here. I built the installer and bootloader on the tutorial , but I registered my services in the wrong place ... before creating the factory controller. Now my bootloader looks like this:

 iocContainer = new WindsorContainer() .Install(FromAssembly.This()); var controllerFactory = new WindsorControllerFactory(iocContainer.Kernel); ControllerBuilder.Current.SetControllerFactory(controllerFactory); iocContainer.Register( Component.For<IUnitOfWorkFactory>() .ImplementedBy<NHUnitOfWorkFactory>() .LifestyleSingleton() ); 

... and my property injections were no longer null .... now I just need to debug the other 87 problems ...

+6
source share
1 answer

Both constructor and property nesting work when the root object is resolved by the container. In this case, your AccountController will be the root object that Windsor should create.

To bind this, you must use a factory controller . After the controller is registered and authorized by the container, everything should work as you expect.

+6
source

All Articles