Unity 工厂注入 [英] Unity Factory Injection

查看:40
本文介绍了Unity 工厂注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像下面这样的接口,我将它注入到统一容器中.

I have an interface like the below one which I inject into unity container.

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

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

All IMyInstance are known before runtime i.e they can be setup within the bootstrapper and can be retrieved from unity. My concrete implementation for IMyInstanceFactory is as below:

public class MyInstanceFactory:IMyInstanceFactory
{
    IUnityContainer _container;

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

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

..and in my bootstrapper I do something like this:

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

这很好地解决了所有问题.但是,我不想依赖容器本身或仅为此实现 IMyInstanceFactory,有没有一种方法可以在不实现 IMyInstanceFactory 的情况下进行设置?Unity 是否为此提供了便利?

This resolves everything beautifully. However, I do not want to take a dependency on the the container as such or implement IMyInstanceFactory just for this, is there a way I can set this up without implementing IMyInstanceFactory? Does Unity provide a facility for this?

这种东西..

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

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

I know castle can do this, can Unity do something similar?

推荐答案

Castle Windsor Typed Factory Facilities for Unity 的端口.它将生成您的接口的实现并为您执行 ResolveAll.

There is a port of the Castle Windsor Typed Factory Facilities for Unity. It will generate an implementation of your interface and do the ResolveAll for you.

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

Your bootstrapping code should look something like this:

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

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

The call to GetAll will be translated to the container call ResolveAll.

端口遵循为 Windsor 描述的相同约定.

The port follows the same conventions described for Windsor.

这篇关于Unity 工厂注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆