如何配置Unity Container以解决多重依赖?

时间:2017-04-03 10:48:53

标签: .net dependency-injection unity-container

我正在尝试在我的.Net应用程序上实现DI。我的数据访问层中有3个API类。我必须一次使用其中任何一个。我试图把有条件的统一分辨率但不确定如何实现它。请一些正文帮我提供示例代码,以便有条件地管理我的3个注入类。

目前我刚刚以下列方式注册了我的课程 -

            IUnityContainer _container = new UnityContainer(); 
            _container.RegisterType(typeof(IPolicyAdminApi), typeof(SomeApiclass1)); 
            _container.RegisterType(typeof(IPolicyAdminApi), typeof(SomeApiclass2)); 
            _container.RegisterType(typeof(IPolicyAdminApi), typeof(SomeApiclass3)); 
            IPolicyAdminApi policyAdmin = _container.Resolve<IPolicyAdminApi>(); 
            return policyAdmin;

2 个答案:

答案 0 :(得分:1)

Unity支持命名注册以允许这种消除歧义,因此您可以像这样编写注册码:

IUnityContainer _container = new UnityContainer(); 
_container.RegisterType("A", typeof(IPolicyAdminApi), typeof(SomeApiclass1)); 
_container.RegisterType("B", typeof(IPolicyAdminApi), typeof(SomeApiclass2)); 
_container.RegisterType("C", typeof(IPolicyAdminApi), typeof(SomeApiclass3)); 
IPolicyAdminApi policyAdmin = _container.Resolve<IPolicyAdminApi>("A"); 
return policyAdmin;

您可以使用Unity Dependency属性指定所需的注册:

public SomeConstructor([Dependency("A")] IPolicyAdminApi api)
{
}

答案 1 :(得分:1)

正如另一个答案所示,UnityIoC的解决方案是Named Registration,与工厂相结合。你可以做一个典型的工厂模式,但是我所做的,全面依赖注入,是注入工厂,作为一个功能:

在注册中:

// Register the named instances.
_container.RegisterType<IPolicyAdminApi, SomeApiclass1>("Name1"); 
_container.RegisterType<IPolicyAdminApi, SomeApiclass2>("Name2"); 
_container.RegisterType<IPolicyAdminApi, SomeApiclass3>("Name3"); 

// Register the factory.
_container.RegisterType<Func<string, IPolicyAdminApi>>(
            new InjectionFactory(c =>
                new Func<string, IPolicyAdminApi>(
                    namedInstance => c.Resolve<IPolicyAdminApi>(namedInstance))));

在班级

class ImUsingTheRegistration
{
    private Func<string, IPolicyAdminApi> iPolicyAdminApiFactory;

    public ImUsingTheRegistration(Func<string, IPolicyAdminApi> iPolicyAdminApiFactory)
    {
        this.iPolicyAdminApiFactory = iPolicyAdminApiFactory;
    }

    public void ImAtRunTime()
    {
        string namedInstance = "Name" + Datetime.Now.ToString().Right(1);

        IPolicyAdminApi instance = iPolicyAdminApiFactory(namedInstance);
    }
}

注意:我使用的是通用注册,但它也适用于其他模式。此外,这将失败,因为没有注册4,5,... 0,但你明白了。