我希望能够从温莎容器中创建一个由system.type实例描述的类型的组件的实例。
我意识到我可以做类似:
的事情public object Create(Type type)
{
return globalContainer.Resolve(type);
}
,但我希望能够在不参考容器的情况下执行此操作。我想知道是否可以使用打字的工厂设施来完成此操作?像
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
}
}
下面的代码显示了如何使用温莎进行此操作。但是,我建议不要制作这样的通用工厂。最好只允许创建实现特定接口的组件。
亲切的问候,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());
}
}