Castle Windsor Weak Typed Factory

Posted by JeffN825 on Stack Overflow See other posts from Stack Overflow or by JeffN825
Published on 2011-01-08T23:38:35Z Indexed on 2011/01/08 23:54 UTC
Read the original article Hit count: 176

In a very very limited number of scenarios, I need to go from an unknown Type (at compile time) to an instance of the object registered for that type.

For the most part, I use typed factories and I know the type I want to resolve at compile time...so I inject a Func<IMyType> into a constructor

...but in these limited number of scenarios, in order to avoid a direct call to the container (and thus having to reference Windsor from the library, which is an anti-pattern I'd like to avoid), I need to inject a Func<Type,object>...which I want to internally container.Resolve(type) for the Type parameter of the Func.

Does anyone have some suggestions on the easiest/most straightforward way of setting this up?

I tried the following, but with this setup, I end up bypassing the regular TypedFactoryFacility altogether which is definitely not what I want:

Kernel.Register(Component.For(typeof (Func<Type, object>)).LifeStyle.Singleton.UsingFactoryMethod(
                    (kernel, componentModel, creationContext) => 
                        kernel.Resolve(/* not sure what to put here... */)));

Thanks in advance for any assistance.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET