如何在不引用容器的情况下从System.Type解析

时间:2014-01-28 16:26:13

标签: c# castle-windsor

我希望能够从windsor容器中为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
    }
}

1 个答案:

答案 0 :(得分:1)

下面的代码展示了如何使用Windsor执行此操作。但是我建议不要制作这样的通用工厂。最好只允许创建实现特定接口的组件。

亲切的问候, 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());
    }
}
豫ICP备18024241号-1