Подтвердить что ты не робот

Как внедрить свойство зависимости с помощью 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 для IoC, моя регистрация выглядит так:

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

Когда я разрешаю экземпляр ServiceA, serviceB будет null. Как я могу это решить?

4b9b3361

Ответ 1

У вас есть как минимум два варианта:

Вы можете/должны использовать инъекцию конструктора, для этого вам нужен конструктор:

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 Do? является хорошей отправной точкой для Unity.