简体   繁体   English

使用构造函数注入的DI统一实现

[英]DI implementation with Constructor Injection using unity

i am new in DI pattern...now just learning.i got a code for Constructor Injection using unity. 我是DI模式的新手...现在才刚刚学习。我得到了使用unity进行构造函数注入的代码。 here is the code. 这是代码。

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

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

here we can see CustomerService ctor looking for LoggingService instance but here when we create instance of CustomerService through resolve then we are not passing the instance of LoggingService. 在这里我们可以看到CustomerService ctor正在寻找LoggingService实例,但是在这里,当我们通过resolve创建CustomerService实例时,我们没有传递LoggingService实例。 so tell me how could will work. 所以告诉我怎么会工作。 any one explain it with small complete sample code. 任何人都可以用少量完整的示例代码来解释它。 thanks 谢谢

The code would look something like this: 代码看起来像这样:

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

So when you resolve your ICustomerService interface, unity will return a new instance of CustomerService. 因此,当您解析ICustomerService接口时,unity将返回CustomerService的新实例。 When it instantiates the CustomerService object, it will see that it needs an ILoggingService implementation and will determine that LoggingService is the class it wants to instantiate. 当实例化CustomerService对象时,它将看到它需要ILoggingService实现,并将确定LoggingService是它要实例化的类。

There's more to it, but that's the basics. 还有更多功能,但这是基础。

Update - Added parameter injection 更新 -添加了参数注入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM