dimanche 21 décembre 2014

Where to place business logic layer in relation to data access while providing unit testability by dependency injection?

I am looking for a way to have a separate layer of business logic in a MVC4 app with Entity Framework, without having to inject my (real or fake) database context in it. Right now we have a fake and real database context that derives from IContext, a repository Repository and a controller MyController. The IContext is injected into a controller, and also the repository, with this pattern:



public class MyController : Controller
{
readonly Repository _repo;

/// <summary>
/// Initializes a new instance of the <see cref="Controllers.MyController"/> class which
/// makes use of the real Entity Framework context that connects with the database.
/// </summary>
public MyController()
{
_repo = new Repository();
}

/// <summary>
/// Initializes a new instance of the <see cref="Controllers.MyController"/> class which
/// can make use of a "Fake" Entity Framework context for unit testing purposes.
/// </summary>
/// <param name="db">Database context.</param>
public MyController(IContext db)
{
_repo = new Repository(db);
}
(...)
}


This is set up like that since it is the repository which has method that access the database and need a fake context, while the unit tests aim at the controllers and needs to be instantiated.


Now I am looking for a way to add a business logic class to the project where methods will be put that have business logic. These methods will need information obtained from the data access layer (Repository) as well.


It feels a bit strange to also inject the IContext for the Repository in this business logic layer with the above pattern. E.g.,



BusinessLogic(IContext db)
{
_repo = new Repository(db);
}


I see two ways to avoid this problem:



  1. Call the repository in the controllers and use data obtained as parameters to methods in the business logic layer.

  2. Inject anyway.


I am looking for a good idea to set up the business logic layer in relation to data access and provide unit testability, preferably without having to inject the database context in every class.


Hope someone can provide me with some insights. Thanks.


Aucun commentaire:

Enregistrer un commentaire