【问题标题】:Why is Unity using property injection when resolving a concrete type?为什么 Unity 在解析具体类型时使用属性注入?
【发布时间】:2012-02-03 00:43:54
【问题描述】:

我有一个界面:

 public interface IFoo{ 
     string Bar{ get; set; } 
 }

以及接口的实现

public class RealFoo{
    public string Bar{ get; set; }
    public string Qux{ get; set; }
}

我已经通过配置文件配置了 unity,以使用属性注入将 IFoo 解析为 RealFoo:

<register type="Namespace.IFoo, Assembly" mapTo="Namespace.RealFoo, Assembly">
    <property name="Qux" value="somevalue" />
</register>

如果我调用 Resolve(typeof(RealFoo)),我的实例将 .Qux 设置为“somevalue”。这怎么可能?这是预期的行为吗?我知道如果我调用 Resolve(typeof( IFoo )) .Qux 将被设置为“somevalue”,但无法解释如何解析具体类型将设置 .Qux。

【问题讨论】:

    标签: .net unity-container


    【解决方案1】:

    当使用统一注册和注入参数/构造函数时,您正在为其映射到的类型定义它们。我不统一使用配置文件,但在代码中它允许您执行以下操作:

    unityContainer.RegisterType<IFoo, FooOne>("FooOne" new InjectionProperty("Qux", "somevalue"));
    unityContainer.RegisterType<IFoo, FooTwo>("FooTwo", new InjectionProperty("Qux", "anothervalue"));
    

    意味着不同的混凝土类型可以有不同的注入参数/属性。在统一中,除非注册被命名,否则使用最后注册的具体注入参数。

    考虑以下几点:

    unityContainer.RegisterType<IFoo, FooOne>(new InjectionProperty("Qux", "somevalue"));
    unityContainer.RegisterType<FooOne>(new InjectionProperty("Qux", "anothervalue"));
    

    如果我随后做了unityContainer.Resolve&lt;IFoo&gt;()unityContainer.Resolve&lt;FooOne&gt;() 两者都将“anothervalue”注入“Qux”,因为它解析为FooOne 实例并且最后一次注册注入“Qux”作为“anothervalue”。

    【讨论】:

    • 谢谢,Lukazoid。我接受了你的回答。当然,这就是它的工作原理,当你解释它时,它是有道理的。我认为最初可能是这种情况,但不确定这不是错误,因为如果 FooOne 仅在映射注册的“到”侧(例如 @mapTo),unityContainer.IsRegistered 返回 false,但如果 unityContainer.IsRegistered 在映射注册的“从”一侧(例如 @type),则返回 true。
    【解决方案2】:

    您还期望它做什么?它为您注入依赖项。 Qux 是一个依赖项。如果您不希望它这样做,请告诉它。此行为与其对构造函数的行为一致。

    【讨论】:

    • 我怀疑你没有仔细阅读这个问题。作者希望看到QuxIFoo 被传递给resolved 时被初始化,但不是在RealFoo 被传递时。
    • 我读得很好。我怀疑你没有仔细阅读我的回答。他的期望是错误的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多