如何使用Ioc的团结
问题描述:
注入依赖属性我有以下类别:如何使用Ioc的团结
public interface IServiceA
{
string MethodA1();
}
public interface IServiceB
{
string MethodB1();
}
public class ServiceA : IServiceA
{
public IServiceB serviceB;
public string MethodA1()
{
return "MethodA1() " +serviceB.MethodB1();
}
}
public class ServiceB : IServiceB
{
public string MethodB1()
{
return "MethodB1() ";
}
}
我使用统一的IoC的,我的注册看起来像这样:
container.RegisterType<IServiceA, ServiceA>();
container.RegisterType<IServiceB, ServiceB>();
当我解决ServiceA
例如, serviceB
将是null
。 我该如何解决这个问题?
答
您至少有两个选项:
可以/应该使用构造函数注射,你需要一个构造函数:
public class ServiceA : IServiceA
{
private IServiceB serviceB;
public ServiceA(IServiceB serviceB)
{
this.serviceB = serviceB;
}
public string MethodA1()
{
return "MethodA1() " +serviceB.MethodB1();
}
}
或Unity支持财产注射,你需要的属性和DependencyAttribute
:
public class ServiceA : IServiceA
{
[Dependency]
public IServiceB ServiceB { get; set; };
public string MethodA1()
{
return "MethodA1() " +serviceB.MethodB1();
}
}
MSDN网站What Does Unity Do?是团结的良好起点。
如果你有构造函数和属性注入的选择,我认为你应该选择构造函数注入。属性注入将使类依赖于统一或某些其他调用者'记住'他们需要提供该依赖关系。构造函数注入使任何试图使用该类的依赖对于该类都至关重要的人都清楚。 – Carlos 2012-04-23 16:40:56
如果类有多个依赖项,那么在某些调用中并不需要这些依赖项?他们都会被实例化吗?或者它们只会在被访问时才被实例化,如上所示:serviceB.method()? @Carlos – Legends 2015-04-12 14:10:02
@Legends当你创建了ServiceA时,即使你没有在你的所有方法中使用它们,你的所有依赖关系也将被设置并注入。 Unity不支持开箱即用的懒惰实例化,但可以将其作为扩展添加:http://pwlodek.blogspot.hu/2010/05/lazy-and-ienumerable-support-comes-to.html – nemesv 2015-04-12 16:26:09