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

本文关键字:依赖 属性 注入 Unity 何使用 Ioc | 更新日期: 2023-09-27 18:32:04

我有以下类:

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,我的注册如下所示:

container.RegisterType<IServiceA, ServiceA>(); 
container.RegisterType<IServiceB, ServiceB>(); 

当我解析ServiceA实例时,serviceBnull.我该如何解决这个问题?

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

这里至少有两个选项:

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

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 网站 Unity 做了什么?是 Unity 的一个很好的起点。