I’m trying to understand which objects should be injected into an object and which should be created internally.
- 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 ?
- 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.