0

私はDIパターンの初心者です...今は学習中です。Unityを使用してコンストラクターインジェクションのコードを取得しました。これがコードです。

public class CustomerService
{
  public CustomerService(LoggingService myServiceInstance)
  { 
    // work with the dependent instance
    myServiceInstance.WriteToLog("SomeValue");
  }
} 

IUnityContainer uContainer = new UnityContainer();
CustomerService myInstance = uContainer.Resolve<CustomerService>();

ここでは、CustomerService ctorがLoggingServiceインスタンスを探しているのを見ることができますが、ここでは、resolveを介してCustomerServiceのインスタンスを作成するときに、LoggingServiceのインスタンスを渡していません。だから、どのように機能するのか教えてください。誰もが小さな完全なサンプルコードでそれを説明します。ありがとう

4

1 に答える 1

2

コードは次のようになります。

public interface ILoggingService
{
    void WriteToLog(string logMsg);
}

public class LoggingService : ILoggingService
{
    public void WriteToLog(string logMsg)
    {
        ... WriteToLog implementation ...
    }
}

public interface ICustomerService
{
    ... Methods and properties here ...
}

public class CustomerService : ICustomerService
{

    // injected property
    public ISomeProperty SomeProperty { get; set; }

    public CustomerService(ILoggingService myServiceInstance)
    { 
        // work with the dependent instance
        myServiceInstance.WriteToLog("SomeValue");
    }
} 

...
...

// Bootstrap the container. This is typically part of your application startup.
IUnityContainer container = new UnityContainer();
container.RegisterType<ILoggingService, LoggingService>();

// Register ICustomerService along with injected property
container.RegisterType<ICustomerService, Customerservice>(
                            new InjectionProperty("SomeProperty", 
                                new ResolvedParameter<ISomeInterface>()));
...
...

ICustomerService myInstance = container.Resolve<ICustomerService>();

したがって、ICustomerServiceインターフェースを解決すると、unityはCustomerServiceの新しいインスタンスを返します。CustomerServiceオブジェクトをインスタンス化すると、ILoggingServiceの実装が必要であることがわかり、LoggingServiceがインスタンス化するクラスであると判断されます。

それだけではありませんが、それが基本です。

更新-パラメータインジェクションを追加

于 2013-01-21T20:46:49.767 に答える