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

编程入门 行业动态 更新时间:2024-10-24 13:21:30
本文介绍了如何将依赖注入实现接口的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

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

本文发布于:2023-11-14 10:24:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586960.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   接口

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!