I want to be able to create an instance of a component from the windsor container for the type described by a System.Type instance.
I realise I can do something like:
public object Create(Type type)
{
return globalContainer.Resolve(type);
}
But I want to be able to do this without refering to the container. I was wondering whether this could be done using the typed factory facility? Something like
public interface IObjFactory
{
object Create(Type type);
}
public class Installer: IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<IObjFactory>().AsFactory());
}
}
public class Something
{
private readonly IObjFactory objFactory;
public Something(IObjFactory objFactory)
{
this.objFactory = objFactory;
}
public void Execute(Type type)
{
var instance = objFactory.Create(type);
// do stuff with instance
}
}
The code below shows how you can do this with Windsor. I would however recommend against making such a generic factory. It is probably better to only allow creation of components implementing a specific interface.
Kind regards, Marwijn.
public interface IObjFactory
{
object Create(Type type);
}
public class FactoryCreatedComponent
{
}
public class Installer : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<TypedFactoryFacility>();
container.Register(
Component.For<FactoryCreatedComponent>(),
Component.For<IObjFactory>().AsFactory(new TypeBasedCompenentSelector()));
}
}
public class TypeBasedCompenentSelector : DefaultTypedFactoryComponentSelector
{
protected override Type GetComponentType(MethodInfo method, object[] arguments)
{
return (Type) arguments[0];
}
}
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.Install(new Installer());
var factory = container.Resolve<IObjFactory>();
var component = factory.Create(typeof (FactoryCreatedComponent));
Debug.Assert(typeof(FactoryCreatedComponent) == component.GetType());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.