using DI to load repository instance on each mvc request

.net, asp.net-mvc, c#, dependency-injection

Solution

The main idea behind DI is to force you to see the big picture instead of concrete implementations.

Your controller needs to get the user, but it shouldn't care about concrete implementation (does your repository fetch the user from the database, web service, xml file, etc. or does it use Linq2Sql, EntityFramework, Dapper or something else under the hood).

Your controller is dependent on that piece of code which can be injected in constructor, property or method, but it doesn't really care about concrete implementation.

DI removes the tight coupling between your controller and repository, allows you to write unit tests by mocking the repository, and you can easily change the concrete implementation of your repository (eg. use PetaPoco instead of EntityFramework) without touching the rest of the code.

You should also take a look at the SOLID principles: http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)

Problem

I read on this post that they are using dependency injection to load repository instance on each mvc request. I'm not sure if I understand correctly but I currently using in my mvc app. `UserRepository` which implements `IUserRepository` interface. This interface is injected in controller constructor ``` public class UserController : Controller { private IUserRepository repository; public UserController(IUserRepository rep) { repository = rep; } public UserController() : this(new UserRepository()) {} } ``` but I don't see any benefit using this interface (`IUserRepository`) I could use `UserRepository` without interface. Obviously someone smarter is figured that is right approach (I've found it on apress mvc4 book) and I would kindly ask someone to elaborate why is this better approach instead of using repository without interface. Having this in mind I would ask anyone to share concrete examples or links on how to implement this approach (using dependency injection to load repository instance on each mvc request).

Original source

Related problems