如何使用Ioc Unity注入依赖项属性

Jin*_* Ho 11 c# ioc-container inversion-of-control unity-container property-injection

我有以下课程:

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() ";
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用Unity for IoC,我的注册看起来像这样:

container.RegisterType<IServiceA, ServiceA>(); 
container.RegisterType<IServiceB, ServiceB>(); 
Run Code Online (Sandbox Code Playgroud)

当我解析一个ServiceA实例时,serviceB将是null.我该如何解决这个问题?

nem*_*esv 18

这里至少有两个选项:

你可以/应该使用构造函数注入,因为你需要一个构造函数:

public class ServiceA : IServiceA
{
    private IServiceB serviceB;

    public ServiceA(IServiceB serviceB)
    {
        this.serviceB = serviceB;
    }

    public string MethodA1()
    {
        return "MethodA1() " +serviceB.MethodB1();
    }
}
Run Code Online (Sandbox Code Playgroud)

或者Unity支持属性注入,因为你需要一个属性和DependencyAttribute:

public class ServiceA : IServiceA
{
    [Dependency]
    public IServiceB ServiceB { get; set; };

    public string MethodA1()
    {
        return "MethodA1() " +serviceB.MethodB1();
    }
}
Run Code Online (Sandbox Code Playgroud)

MSDN网站Unity做什么?是Unity的一个很好的起点.

  • 如果您可以在构造函数和属性注入之间进行选择,我认为您应该选择构造函数注入.属性注入将使类依赖于统一或其他一些调用者"记住"他们需要提供该依赖.构造函数注入使任何试图使用类的人都清楚,依赖对于类是必不可少的. (6认同)