Search code examples
c#unit-testingdependency-injectionloose-coupling

I know how to use dependency injection but I recognize no practical advantage for it


It is about this (Inject the dependency)

private readonly ICustomerService _customerService;
public Billing(ICustomerService customerService)
{
   _customerService = customerService;
}

versus this (Create the dependency)

private readonly ICustomerService _customerService;
public Billing()
{
   _customerService = new CustomerService();
}

The latter sample so they say is bad because... it violates DI...of course nothing is injected... but what if DI would not exist, what is so bad that the CustomerService is created manually from the Billing class? I see no practical advantage concerning exchangeability of the Service interface.

I ask for a practical example with source code may it be a unit test or showing a practical solution why it is so much more loose coupling.

Anyone keen enough to show his DI muscles and why it has a practical right to exist and be applied?

UPDATE

So people have not to read all up I will write here my short experience:

DI as a pattern has a practical usage. To follow DI by not injecting all services manually (a poor mans DI tool so they say...) use a DI framework like LightCore/Unity but be sure you use the right tool for the appropriate job. This is what I did not;-) Developing a mvvm/wpf application I have other requirements the LightCore/Unity tool could not support they even were a barrier. My solutions was to use MEFEDMVVM with which I am happy. Now my services are automatically injected at runtime not at startup time.:-)


Solution

  • Imagine that CustomerService connects to your CRM system and your database. It creates a whole bunch of network connections to retrieve data about the customer and maybe reads additional things from the database to augment that before returning the data to the Billing class to use in its calculation.

    Now you want to unit test Billing to make sure the calculations it's making are correct (you don't want to send out wrong bills right?)

    How will you unit test Billing if its constructor is tied to a class that requires connections to a real CRM system and database? Wouldn't it be better to inject that dependency as an interface, easily allowing you to provide a mock version for your tests?

    That is why DI is useful.