0

我是 DI 模式的新手……现在刚刚学习。我得到了一个使用统一的构造函数注入代码。这是代码。

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 实例,但是在这里,当我们通过解析创建 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 回答