如何使用Ioc Unity注入依赖项属性 [英] How to inject dependency property using Ioc Unity
本文介绍了如何使用Ioc Unity注入依赖项属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下课程:
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() ";
}
}
我使用Unity for IoC,我的注册如下:
I use Unity for IoC, my registration looks like this:
container.RegisterType<IServiceA, ServiceA>();
container.RegisterType<IServiceB, ServiceB>();
当我解析ServiceA
实例时,serviceB
将是null
.
我该如何解决?
When I resolve a ServiceA
instance, serviceB
will be null
.
How can I resolve this?
推荐答案
您在这里至少有两个选择:
You have at least two options here:
您可以/应该使用构造函数注入,因为您需要构造函数:
You can/should use constructor injection, for that you need a constructor:
public class ServiceA : IServiceA
{
private IServiceB serviceB;
public ServiceA(IServiceB serviceB)
{
this.serviceB = serviceB;
}
public string MethodA1()
{
return "MethodA1() " +serviceB.MethodB1();
}
}
或者Unity支持属性注入,为此您需要一个属性和DependencyAttribute
:
Or Unity supports property injection, for that you need a property and the DependencyAttribute
:
public class ServiceA : IServiceA
{
[Dependency]
public IServiceB ServiceB { get; set; };
public string MethodA1()
{
return "MethodA1() " +serviceB.MethodB1();
}
}
MSDN网站 Unity做什么?是一个很好的Unity起点.
The MSDN site What Does Unity Do? is a good starting point for Unity.
这篇关于如何使用Ioc Unity注入依赖项属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文