IoC容器.注入容器 [英] IoC Container. Inject container

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

问题描述

我想要的是:解析对象A,并且在对象A内,我想使用相同的容器来解析对象C:

What I want: Resolve object A, and inside object A, I want use same container to resolve object C:

public static void Work()
{
    IUnityContainer con = new UnityContainer();
    con.RegisterType<IA, A>();
    con.RegisterType<IB, B>();
    con.RegisterType<IC, C>();

    var a = con.Resolve<IA>();
}


interface IA { }
interface IB { }
interface IC { }

class A : IA
{
    public A(IB b, IUnityContainer con)
    {
        for (int i = 0; i < 10; i++)
        {
            var c = con.Resolve<IC>();
        }
    }
}

class B : IB { };
class C : IC { };

问题:在许多站点上,我看到注入容器不是一个好主意,但是在这种情况下又如何呢?

Problem: On many sites I see that injecting container is bad idea, but how to be in such situation?

编辑1

服务定位器是一种反模式.因此,如果可以在IoC容器中使用Service Locator,为什么还可以呢?

Service Locator is an anti-pattern. So if it is okay to use Service Locator with IoC Container, why is it okay?

推荐答案

您不应传递对类的直接引用,因为这将使您的代码依赖于使用的IOC容器(此处为UnityContainer),并且使其变得更难一点用于单元测试.

You should not pass a direct reference to your class, cause this will make your code dependant on the used IOC container (here UnityContainer) and makes it a little harder for unittests.

如果您的类A需要多个C实例,则应为此情况定义一个工厂,并将该工厂的实例传递给您的类A.您的真实工厂可以引用UnityContainer.对于单元测试,您可以模拟接口并将模拟的实例传递给类A.

If your class A needs multiple instances of C you should define a factory for this case and pass an instance of that factory to your class A. Your real factory can reference the UnityContainer. For unittests you can mock the interface and pass a mocked instance to your class A.

此代码看起来像这样.

public interface IClassICFactory
{
    IC CreateInstance();
}

public class ClassICUnityContainerFactory : IClassCFactory
{
    private IUnityContainer _container;

    public ClassICUnityContainerFactory(IUnityContainer container)
    {
        _container = container;
    }

    public IC CreateInstance()
    {
        return _container.Resolve<C>();
    }
}

class A : IA
{
    public A(IB b, IClassICFactory factory)
    {
        for (int i = 0; i < 10; i++)
        {
            var c = factory.CreateInstance();
        }
    }
}

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

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