【问题标题】:DI implementation with Constructor Injection using unity使用统一的构造函数注入实现 DI
【发布时间】:2013-01-21 19:37:48
【问题描述】:

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

【问题讨论】:

  • 您的要求并不完全清楚。据推测 LoggingService 将是一个接口,而不是具体类型,并且当您引导容器时,您将为它提供从 LoggingService 接口到具体类型的映射。当您要求容器解析 CustomerService 时,它​​会看到构造函数采用 LoggingService 接口并尝试解决该接口,然后将 LoggingService 的实例传递给构造函数。
  • 您真正需要的是 ICustomerService 和 ILoggingService 接口,而这些正是您要解决的。当您引导容器时,您将创建从 ICustomerService 到 CustomerService 和 ILoggingService 到 LoggingService 的映射
  • 你能否提供完整的小代码,这样我可以更好地可视化,因为我在 DI 方面很弱。

标签: c# dependency-injection unity-container


【解决方案1】:

代码如下所示:

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 是它要实例化的类。

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

更新 - 添加参数注入

【讨论】:

  • 您能否提供另一个示例代码,用于使用 setter 而不是构造函数进行依赖注入。只需复制您的第一个代码并进行一些更改以使用 setter 实现它。谢谢
  • 我在示例中添加了属性注入的示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多