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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10267536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:06:25  来源:igfitidea点击:

How to inject dependency property using Ioc Unity

c#inversion-of-controlunity-containerioc-containerproperty-injection

提问by Jin Ho

I have the following classes:

我有以下课程:

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() ";
    }
}

I use Unity for IoC, my registration looks like this:

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

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

When I resolve a ServiceAinstance, serviceBwill be null. How can I resolve this?

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

采纳答案by nemesv

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();
    }
}

Or Unity supports property injection, for that you need a property and the DependencyAttribute:

或者 Unity 支持属性注入,为此您需要一个属性和DependencyAttribute

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

    public string MethodA1()
    {
        return "MethodA1() " +serviceB.MethodB1();
    }
}

The MSDN site What Does Unity Do?is a good starting point for Unity.

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