Sco*_*ach 3 c# dependency-injection unity-container
当我
container.RegisterType<IInterface, MyClass>();
Run Code Online (Sandbox Code Playgroud)
一切正常,所有依赖属性都注释为:
[Dependency]
Run Code Online (Sandbox Code Playgroud)
通过容器解决.
但是,我现在有一个int属性,我也想通过容器来解决.它不是在构造函数中传递的,而是作为公共属性传递的.所以我尝试了这个:
container.RegisterType<IInterface, MyClass>(
new InjectionProperty("PropertyName", 1)
);
Run Code Online (Sandbox Code Playgroud)
现在该属性被注入,但使用[Dependency]注释的所有其他属性都为null并且未解析.如果我将InjectionProperty用于一个属性,我现在是否必须显式声明具有[Dependency]属性的所有其他属性?或者有更好的方法吗?
谢谢.
虽然@najmeddine是正确的,但您仍然可以执行以下操作.
你的组件:
public class Service : IService
{
[Dependency("Key")]
public Int32 Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
注册:
IUnityContainer unity = new UnityContainer()
.RegisterType<IService, Service>()
.RegisterInstance("Key", 2010)
Run Code Online (Sandbox Code Playgroud)
用法很简单.
如果您现在使用Unity 2.0或更高版本(不适用于您),并且您需要在应用程序的不同区域(有界上下文)中注入不同的值,请使用容器层次结构:
IUnityContainer child = unity.CreateChildContainer()
.RegisterInstance("Key", 1900);
Run Code Online (Sandbox Code Playgroud)
并在child
Unity Container 上解析您的组件.
有关容器层次结构的更多信息:http: //msdn.microsoft.com/en-us/library/ff660895 (PandP.20).aspx