Search code examples
c#design-patternsarchitecturedependency-injectionservice-layer

Inject Dependencies without Interfaces Defined nLayer


I have an n-layered application (DAL, BLL, Service Layer, and UI) that we are redeveloping with a new UI layer that will use MVC and inject service class dependencies in controllers. I believe we can achieve loose coupling with UI and Service Layer, but the DAL and BLL classes are inherited from an existing/old code base and do not have any interfaces defined for each class. An example of a service class looks like below:

public class OrderService : IOrderService
{
    OrderBL _orderBL = new OrderBL();

    public void OrderSomething(int somethingID) { _orderBL.DoSomething(somethingID); ... }
    ...
}

As you can see the OrderService has a direct dependency on OrderBL. In my limited understanding of architecture/patterns, this seems to go against DI principles. Unfortunately, we cannot directly modify the BLL and DAL at this time. So my question is how would you deal with this situation to still achieve loose coupling between business layer and service layer?


Solution

  • Don't modify the behaviour of your BLL and DAL... just use the built in tools to extract interfaces for them: Extracting an Interface - MSDN (by "directly modify", I assume you mean completely refactor).

    Then you will have interfaces with which you can start re-implementing as you fix up the BLL and DAL later on down the track.

    There is no other way around the tight coupling here. If you must instantiate an object directly.. you've automagically coupled them. At least once you extract interfaces, your dependencies become inverted (see: Dependency Inversion Princple) and they can be injected into your services.