使用Unity进行构造函数注入的DI实现

时间:2013-01-21 19:37:49

标签: c# dependency-injection unity-container

我是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的实例。所以告诉我怎么会有用。任何人用小的完整示例代码解释它。感谢

1 个答案:

答案 0 :(得分: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是它想要实例化的类。

还有更多内容,但这是基础知识。

更新 - 添加参数注入