根据DI原则应该注射为C'tor参数? [英] What should be injected as C'tor paramter under DI principles?

查看:142
本文介绍了根据DI原则应该注射为C'tor参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 如果我有一些,那么我想了解哪些对象应该被注入到一个对象中, 列出< int> (作为数据字段),它保存运行时收集的信息。似乎我应该在c'tor中启动它,而不是注入它。

但是,通过一个COM端口。



我是否让HW类初始化SerialPort或注入?


  1. 如果上述SerialPort需要注入;什么是最好的方法?

我是否手动创建它:



SerialPort端口=新的SerialPort(名称,波特率...);

  

HWClass hwClass = container.Reolve< IHWClass>(HWClass,新的InjectionConstructor(port));

或使用Unity容器

  SerialPort port = conatiner.Resolve< SerialPort>(...); 

HWClass hwClass = container.Reolve< IHWClass>(HWClass,新的InjectionConstructor(port));

或者我应该在HWClass C'tor中启动它?



阿迪尔

解决方案

域驱动设计区分服务和其他Domain对象(实体值对象)。即使你没有订阅DDD,这个区别是非常有用的。



服务通常是长寿命的,无状态的对象,执行为消费者开展业务。它们是典型的依赖关系,您可以从注入中获益很大。



在您的情况下,SerialPort和IHwClass都听起来非常像服务,因为它们代表外部资源,所以我将通过构造函数注入 来确保注入。



但是,只有真正获得如果您注入抽象,则松散耦合的优点。 IHWClass看起来很好,因为它是一个接口,但是SerialPort看起来像一个具体的类,所以你注意不到很多。 从SerialPort(例如ISerialPort)中提取界面,然后注入会更好。


I'm trying to understand which objects should be injected into an object and which should be created internally.

  1. If i have some List<int> (as data field) which holds infomation gathered during run time. it seems that i should init it in the c'tor instead of injecting it.

but what about a hardware class which communicates through a COM port.

do i let the HW class init the SerialPort or i inject it ?

  1. If the above mentioned SerialPort needs to be injected; what is the best way to do it ?

do i create it manually :

SerialPort port = new SerialPort(name, baud ...);

HWClass hwClass = container.Reolve<IHWClass>("HWClass", new InjectionConstructor(port));

or using the Unity container

SerialPort port = conatiner.Resolve<SerialPort>(...);

HWClass hwClass = container.Reolve<IHWClass>("HWClass", new InjectionConstructor(port));

or should i init it inside the HWClass C'tor ?

adiel

解决方案

Domain-Driven Design distinguishes between Services and other Domain objects (Entities and Value Objects). Even if you don't otherwise subscribe to DDD, this distinction is very useful.

Services are typically long-lived, stateless objects that perform operations for their consumers. They are the typical dependencies that you can benefit greatly from injecting.

In your case, both SerialPort and IHwClass sounds very much like services because they represent external resources, so I would definitely inject them via Constructor Injection.

However, you only really gain the benefit of loose coupling if you inject an abstraction. The IHWClass looks fine because it's an interface, but the SerialPort looks like a concrete class, so you don't gain much from injecting it. Extracting an interface from SerialPort (say, ISerialPort) and injecting that instead would be better.

这篇关于根据DI原则应该注射为C'tor参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆