Unity.Resolve 如何知道使用哪个构造函数?
给定一个具有多个构造函数的类 - 我如何告诉 Resolve 使用哪个构造函数?
考虑以下示例类:
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 类型的对象,Resolve 如何知道要使用哪个构造函数?我怎样才能告诉它使用正确的呢?假设我有一个注册了 IBar 的容器 - 它会理解它应该支持采用 IBar 的构造函数吗?如果我也指定了一个字符串 - 它会使用 (string, IBar)
构造函数吗?
Foo foo = unityContainer.Resolve<Foo>();
请忽略这样一个事实:如果类只有一个构造函数,可能会更容易......
Given a class with several constructors - how can I tell Resolve which constructor to use?
Consider the following example class:
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; }
}
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
摘自 链接文本
Taken from link text
当您注册类型时,您可以指定要使用哪个构造函数,如下所示:
上面的代码来自内存,但这是一般原则。在本例中,我选择了采用 IBar 类型的单个参数的构造函数。
我不能忽略这一点。当谈到构造函数注入时,歧义是一种设计味道。您基本上是在说:我真的不知道我是否关心这种依赖关系。
当然,Unity 可能会为您解决这个问题,但是您将依赖于特定的容器行为而不是正确设计你的 API。 其他容器可能有不同的行为,因此,如果您选择从 Unity 迁移到更好的容器,则可能会出现细微的错误。
在 DI 友好但与容器无关的环境中编写代码要安全得多< /a> 方式。
When you register the type, you can specify which constructor to use like this:
The above code is from memory, but that's the general principle. In this case I've picked the constructor that takes a single parameter of type IBar.
I can't ignore this. When it comes to Constructor Injection, ambiguity is a design smell. You are basically saying: I don't really know if I care about this dependency or not.
Sure, Unity is likely to figure it out for you, but then you would be relying on a specific container behavior instead of properly designing your API. Other containers may have a different behavior, so if you ever choose to migrate from Unity to a better container, subtle bugs may occur.
It's much safer to write your code in a DI-friendly, but container-agnostic manner.