How to inject dependency property using Ioc Unity

2020-07-03 04:46发布

问题:

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:

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

When I resolve a ServiceA instance, serviceB will be null. How can I resolve this?

回答1:

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:

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.