Question

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?

Was it helpful?

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.

OTHER TIPS

It isn't ideal, but you can write a wrapper class for DAL or BLL classes that you need to access from your service layer. Say for example, you have a class Coupled, in assembly CoupledAssembly:

public class Coupled
{
    public int GetAnInteger();
}

You can create interface INoLongerCoupled wherever you are keeping all your interfaces:

public interface INoLongerCoupled
{
    int GetAnInteger();
}

and a wrapper class in a separate assembly, CoupledAssemblyWrapper, that references CoupledAssembly:

public class CoupledAssemblyWrapper : Coupled, INoLongerCoupled
{
}

Register CoupledAssemblyWrapper with your IoC container, and when the time comes to fix up the Coupled class, you can have it implement INoLongerCoupled directly, and get rid of the wrapper.

If the wrapped class is sealed, then you'll have to be a little more clever in your wrapper class, essentially instantiating a copy of Coupled, and re-implementing all of the interface methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top