如何将依赖注入实现接口的类

如何将依赖注入实现接口的类

本文介绍了如何将依赖注入实现接口的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道接口无法定义构造函数。强制所有实现接口的类在同一个合同中接收它们的依赖关系的最佳做法是什么。我知道可以通过属性将依赖项注入到对象中,但是通过构造函数传递它们对我来说更有意义。那么如何DI?

I know interfaces cannot define constructors. What is the best practice to force all classes implementing an interface, to receive their dependencies in a uniform contract. I know ints possible to inject dependencies into objects via properties, but passing them via constructors makes more sense to me. How to DI then ?

推荐答案

我们都知道这可以通过许多不同的方法实现,但更有意义的是肯定会受到欢迎。我定义了一些 set-only 属性,然后该对象负责保存对传递给它的内容的引用:

We all know this is possible by many different methods, but something that makes sense is more welcome surely. I defined some set-only properties, then the object is responsible to holding a reference to what is passed to it:

public interface IBlogRepository
{
    ISession Session { set; }
}

class BlogRepository : IBlogRepository
{
   private ISession m_session;

   ISession Session
   {
      set { m_session = value; }
   }
}

这样每个实现接口的类都知道 set-only 属性是依赖注入,因为很少使用 set-only 属性。我不确定这种方法是否被称为良好做法,但从现在开始对我来说就是这样。

This way every class implementing the interface knows that the set-only property is a dependency injection, since set-only properties are rarely used. I'm not sure if this method is known as a good practice or not, but for me it is, from now.

这篇关于如何将依赖注入实现接口的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:34