web-dev-qa-db-ja.com

IocUnityを使用して依存性プロパティを注入する方法

私は次のクラスを持っています:

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になります。どうすればこれを解決できますか?

12
Jin Ho

ここには少なくとも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サイト nityは何をしますか? はUnityの良い出発点です。

18
nemesv