What should be injected as C'tor paramter under DI principles?

岁酱吖の 提交于 2019-12-01 12:59:57

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.

My general rule is that if the object can have it's state changed from outside your class or you want to be able to supply an alternate implementation either in testing or at some point in the future dynamically, you should inject it. If the class is only used and modified internally and the implementation is only dependent on the containing class, then creating the dependency internally is probably ok. To use your example, I would inject SerialPort, but not the List<int>.

As an aside, now that I do TDD (Test Driven Development), I find that I really don't worry too much about these decisions. You pretty quickly reach that point that you know which classes need to be injected in order to decouple your classes to make testing easier. Even if you don't get it right at first, within a few tests you find your code naturally evolving in that direction.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!