Unity.Resolve如何知道要使用哪个构造函数? [英] How does Unity.Resolve know which constructor to use?

查看:149
本文介绍了Unity.Resolve如何知道要使用哪个构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个包含多个构造函数的类-如何告诉Resolve使用哪个构造函数?

Given a class with several constructors - how can I tell Resolve which constructor to use?

请考虑以下示例类:

public class Foo
{
    public Foo() { }
    public Foo(IBar bar)
    {
        Bar = bar;
    }
    public Foo(string name, IBar bar)
    {
        Bar = bar;
        Name = name;
    }
    public IBar Bar { get; set; }        
    public string Name { get; set; }
}

如果我想使用Resolve创建Foo类型的对象,如何解决知道使用哪个构造函数?我如何告诉它使用正确的呢?假设我有一个已注册IBar的容器-它会理解它应该有利于采用IBar的构造函数吗?而且,如果我也指定一个字符串-它将使用(string,IBar)构造函数吗?

If I want to create an object of type Foo using Resolve how will Resolve know which constructor to use? And how can I tell it to use the right one? Let's say I have a container with an IBar registered - will it understand that it should favor the constructor taking IBar? And if I specify a string too - will it use the (string, IBar) constructor?

Foo foo = unityContainer.Resolve<Foo>(); 

并且请忽略以下事实:如果类只有一个构造函数,这可能会更容易。

And please ignore the fact that it would probably be easier if the class just had a single constructor...

推荐答案


当目标类包含多个构造函数时,Unity将使用具有以下构造函数的构造函数应用了InjectionConstructor属性。如果有多个构造函数,并且没有一个带有InjectionConstructor属性,则Unity将使用参数最多的构造函数。如果存在多个这样的构造函数(具有相同参数数量的多个最长构造函数),则Unity将引发异常。

When a target class contains more than one constructor, Unity will use the one that has the InjectionConstructor attribute applied. If there is more than one constructor, and none carries the InjectionConstructor attribute, Unity will use the constructor with the most parameters. If there is more than one such constructor (more than one of the "longest" with the same number of parameters), Unity will raise an exception.

来自链接文字

这篇关于Unity.Resolve如何知道要使用哪个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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