c# – Unity Factory Injection

我有一个类似下面的界面,我注入到统一容器中.

public interface IMyInstanceFactory
{
    IEnumerable<IMyInstance> GetAll();
}

所有IMyInstance在运行时之前都是已知的,即它们可以在引导程序中设置并且可以从统一中检索.我对IMyInstanceFactory的具体实现如下:

public class MyInstanceFactory:IMyInstanceFactory
{
    IUnityContainer _container;

    public MyInstanceFactory(IUnityContainer container)
    {
        _container = container;
    }
    public IEnumerable<IMyInstance> GetAll()
    {
        return _container.ResolveAll<IMyInstance>();
    }
}

..在我的引导程序中,我做了这样的事情:

container.RegisterType<IMyInstance,MyInstance1>;
container.RegisterType<IMyInstance,MyInstance2>;
container.RegisterType<IMyInstance,MyInstance3>;
container.RegisterType<IMyInstanceFactory,MyInstanceFactory>;

这很好地解决了一切.但是,我不想依赖于容器,或者为此实现IMyInstanceFactory,有没有办法在不实现IMyInstanceFactory的情况下设置它? Unity是否为此提供了便利?

这种东西……

container.RegisterType<IMyInstanceFactory,factory=>factory.GetAll()>().IsResolvedBy(unity.ResolveAll<IMyInstance>);

我知道城堡可以做到这一点,Unity可以做类似的事吗?

解决方法:

a port of the Castle Windsor Typed Factory Facilities for Unity.它将生成您的界面的实现并为您执行ResolveAll.

您的引导代码应如下所示:

container.RegisterType<IMyInstance,MyInstance1>("1");
container.RegisterType<IMyInstance,MyInstance2>("2");
container.RegisterType<IMyInstance,MyInstance3>("3");
container.RegisterType<IMyInstanceFactory>(new TypedFactory());

对GetAll的调用将被转换为容器调用ResolveAll.

该端口遵循与Windsor相同的约定.

上一篇:处理程序“ExtensionlessUrlHandler-Integrated-4.0”在其模块列表中有一个错误模块“ManagedPipelineHandler” •使用了托管的处理程序,但是未


下一篇:Magento2入门之修改logo