指定要使用的Unity IoC容器的构造函数 [英] Specify constructor for the Unity IoC container to use

查看:222
本文介绍了指定要使用的Unity IoC容器的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Unity IoC容器来解析对象。但是,我遇到了一个问题。当我有多个构造函数时-Unity如何知道要使用哪个构造函数?当我有一个有和没有一个时,似乎使用带参数的一个。我可以明确告诉它要使用哪个构造函数吗?

I'm using the Unity IoC container for resolving my objects. However, I've run into an issue. When I have more than one constructor - how does Unity know which one to use? It seems to use the one with parameters when I have one with and one without. Can I explicitly tell it which constructor to use?

具体来说,我有一个类似于以下带有两个构造函数的Person类的案例。在这种情况下,我希望IoC容器使用默认构造函数-不带参数-但它选择带参数的那个。

Specifically I had a case similar to the following Person class with two constructors. In this case I want the IoC container to use the default constructor - without parameters - but it chooses the one with parameters.

public class SomeValueObject
{
    public SomeValueObject(string name)
    {
        Name = name; 
    }
    public string Name { get; set; }
}

public class Person
{
    private string _name; 

    public Person()
    {
        _name = string.Empty;
    }

    public Person(SomeValueObject obj)
    {
        _name = obj.Name;
    }
}

这显然失败了,因为它无法创建SomeValueObject -不知道要向其字符串参数注入什么。它给出的错误是:

This obviously fails as it can't create the SomeValueObject - not knowing what to inject to its string parameter. The error it gives is:


依赖项解析失败,类型= MyApp.Person,名称=。异常消息是:当前的生成操作(生成键Build Key [MyApp.Person,null])失败:尝试调用构造函数MyApp.Person(MyApp.SomeValueObject obj)时无法解析参数obj。 (策略类型为BuildPlanStrategy,索引3)

Resolution of the dependency failed, type = "MyApp.Person", name = "". Exception message is: The current build operation (build key Build Key[MyApp.Person, null]) failed: The parameter obj could not be resolved when attempting to call constructor MyApp.Person(MyApp.SomeValueObject obj). (Strategy type BuildPlanStrategy, index 3)

容器注册:

Container.RegisterType<Person, Person>(new Microsoft.Practices.Unity.ContainerControlledLifetimeManager());

解决:

var person = Container.Resolve<Person>();


推荐答案

注册为:

container.RegisterType<Person>(new InjectionConstructor());

您也可以使用RegisterType方法的重载来添加LifetimeManager。

You can add the LifetimeManager as well using an overload of the RegisterType method.

也就是说,在为DI建模时,如果您具有明确的构造函数(即,没有重载的构造函数),那么您的生活会容易得多。

That said, when modeling for DI, your life will be much easier if you have unambiguous contructors (i.e. no overloaded constructors).

这篇关于指定要使用的Unity IoC容器的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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