views:

334

answers:

3

I have a class that I want to have access to my IOC container (Windsor), however I don't want to keep a static IWindsorContainer property hanging around - I would prefer to have the container inject itself into any classes that require an IWindsorContainer as a constructor dependency.

I've pulled this off with Unity, but when I try the same thing with the Windsor container it tells me that IWindsorContainer is not registered with the container.

I don't think I can just register IWindsorContainer => WindsorContainer, because that will cause the container to create a new (or different) instance of itself to pass to my class, and that instance won't have all my other types registered with it. I also don't see a way to construct the container, register all the types in it, and then register that instance of itself against IWindsorContainer - all of the registration methods only take types for service and implementation - never an actual concrete instance.

+2  A: 

Generally you don't want to inject the container into your application components.

See these questions (this question is almost a duplicate of them):

BTW: you get IKernel injection for free, and you can register IWindsorContainer:

container.Register(Component.For<IWindsorContainer>().Instance(container));
Mauricio Scheffer
A: 

Generally, like mausch said, think twice before you pass your container to your component. Do you really need it to have access to the container?

To pull dependencies from the container use typed factories.

Krzysztof Koźmic
A: 

I was tempted to do this recently. I wanted to be able to create multiple instances of a service during the lifetime of an object. Registering a factory would be better in that the need for the dependency is clearer. But creating a factory per service seemed like a pain.

I ended up using something like the code in this article: http://mikehadlow.blogspot.com/2010/01/10-advanced-windsor-tricks-1a-delegate.html. Suppose you have a class that needs to create instances of IService. The article describes a technique allowing your class to have a dependency on Func, and you'll automatically get a factory specific to that class.

Frank Schwieterman