2009-09-02 33 views
3
当我 一切正常,所有依赖属性注释: 通过容器解析。 但是,我现在有一个int属性,我也想通过容器解析。它不是在构造函数中传递的,而是作为公共属性传递的。所以我尝试了这个: 现在该属性被注入,但所有其他使用[Dependency]注释的属性为null且未解析。如果我将InjectionProperty用于一个属性,我现在是否必须显式声明具有[Dependency]属性的所有其他属性?或者有更好的方法吗? 谢谢。

回答

1

通过API(运行时)注册属性将取消[Dependency]属性。 你不能同时使用两者。但是你可以使用反射来获取用[Dependency]属性装饰的属性,并在运行时注册它们。

6

虽然@najmeddine是正确的,但您仍然可以执行以下操作。

你的组件:

public class Service : IService 
{ 
    [Dependency("Key")] 
    public Int32 Value { get; set; } 
} 

报名:

IUnityContainer unity = new UnityContainer() 
    .RegisterType<IService, Service>() 
    .RegisterInstance("Key", 2010) 

用法很简单。

如果你现在使用统一2.0或更高版本(这是不适用于你)如果你需要注入你的应用程序在不同的地区不同的值(限界上下文),使用容器层次:

IUnityContainer child = unity.CreateChildContainer() 
    .RegisterInstance("Key", 1900); 

并解决你的组件在child Unity容器。

更多关于容器层次: http://msdn.microsoft.com/en-us/library/ff660895(PandP.20).aspx

0

正如najmeddine表示,InjectionProperty注册覆盖[Dependency]属性...你可以,但是,仍然使用InjectionMethod对象不会覆盖[Dependency]属性。

我建立了我与可选的 “覆盖” 方法的对象:

class SomeObject 
{ 
    [Dependency("Value")] 
    public string Value { get; set; } 

    public void OverrideValue(string value) 
    { 
     this.Value = value; 
    } 
} 

普通DI将工作如下:

container.RegisterInstance<string>("Value", "Default Value"); 

container.Resolve<SomeObject>(); 

随着覆盖的值,你会做以下几点:

container.RegisterType<SomeObject>("NotDefault", new InjectionMethod("OverrideValue", "Other Value")); 

container.Resolve<SomeObject>("NotDefault"); 

我刚刚写下了我的头顶,所以我提前为任何错别字道歉。 (如果您发现任何内容,只需发表评论,我会很乐意调整我的答案。)