13

次のクラスがあります。

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

私は IoC に Unity を使用しています。私の登録は次のようになります。

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

ServiceAインスタンスを解決すると、serviceBになりますnull。どうすればこれを解決できますか?

4

1 に答える 1

19

ここには、少なくとも 2 つのオプションがあります。

コンストラクターが必要なため、コンストラクター注入を使用できます/使用する必要があります。

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 サイトWhat Does Unity Do? Unity の良い出発点です。

于 2012-04-22T11:33:37.793 に答える