问题描述
考虑以下代码示例:
public interface IMyInterface
{
void SetName(string name);
string GetName();
}
public class MyInterfaceImplementor1 : IMyInterface
{
protected string Name { set; get; }
public void SetName(string name)
{
this.Name = name;
}
public virtual string GetName()
{
return this.Name;
}
}
public class MyInterfaceImplementor2 : MyInterfaceImplementor1
{
public override string GetName()
{
return String.Format("Hello! {0}", base.Name);
}
}
为此的DI配置:(
And the DI configuration for this: (StructureMap code snippet provided)
ObjectFactory.Configure(x =>
{
x.For<IMyInterface>()
.Use<MyInterfaceImplementor1>();
});
ObjectFactory.Configure(x =>
{
x.For<IMyInterface>()
.Use<MyInterfaceImplementor2>();
});
说,在我的代码中,有时我正在使用 MyInterfaceImplementor1 在其他时候,我使用 MyInterfaceImplementor2 。我的问题是,DI框架(StructureMap或其他任何框架)将如何解决上述配置?另外,它将如何确定在哪里返回 MyInterfaceImplementor1 的实例以及何时在 MyInterfaceImplementor2 处返回相同的实例?还是我在这里做错了?
Say, in my code, at some point I am using MyInterfaceImplementor1 and at some other point, I use MyInterfaceImplementor2. My question is, how the DI framework (StructureMap or any other) will resolve the above configuration? Also, how will it determine, where to return an instance of MyInterfaceImplementor1 and when the same of MyInterfaceImplementor2? OR Am I doing something wrong here?
推荐答案
在您的情况下,StructureMap将解析 MyInterfaceImplementor2 。 StructureMap存储所有注册,但使用 Use()方法解析最后一个注册。
In your case StructureMap will resolve MyInterfaceImplementor2. StructureMap stores all registrations but resolves the last one registered with Use() method.
插件类型-要注入的类型,在大多数情况下,它是一个接口,但SM还会解析具体类型(即使您尚未注册)
Plugin type - type that is to be injected, in most of the cases it is an interface but SM resolves also concrete types (even if you haven't registered them)
插入式/混凝土类型-插件类型的实现
c.For<IPluginType>().Use<ConcreteType>();
通常在SM中,有两种手动注册类型。您可以使用 Add()和 Use()方法注册依赖项。
Generally in SM there are 2 types of manual registration. You can register dependencies with Add() and Use() method.
有什么区别?
- Add()仅在插件家族中注册具体类型
- Use()注册并将其设置为解析插件类型时要使用的默认注册
- Add() just registers concrete type in plugin family
- Use() registers and sets it as default registration to be used when resolving plugin type
对于添加()有一个约定,当您只有一个注册时,它将被解决。如果有多个注册容器在尝试解析插件类型时会抛出 StructureMapException 。
For Add() there is a convention that when you have only one registration then it will be resolved. In case when there is more than one registration container would throw StructureMapException when trying to resolve plugin type.
csprabala答案很好地解释了多种实现方式应该在StructureMap中注册。
csprabala answer provides good explanation how multiple implementations should be registerd within StructureMap.
当我有多种插件类型的实现时,我总是使用 Add()方法注册,如果有默认实现我用 Use()
When I have multiple implementations of plugin type I always register the with Add() method and if there is a default implementation I register it with Use()
这篇关于DI框架如何解决具有多个配置的同一接口的依赖性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!