使用DI加载库实例上的每一个MVC请求实例、加载、DI、MVC

2023-09-04 22:37:22 作者:我们终成陌生人

我读这个帖子他们使用依赖注入来加载库实例上的每一个MVC请求。

I read on this post that they are using dependency injection to load repository instance on each mvc request.

我不知道如果我理解正确的,但我目前使用在我的MVC应用程序。 UserRepository 它实现 IUserRepository 接口。此接口的控制器构造函数中注入

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()) {}
}

但我任何好处,通过这个接口( IUserRepository )我可以使用 UserRepository 无界面看不到。显然,聪明的人是计算过,是正确的做法(我发现它在preSS mvc4书),我谨请别人来阐述为什么这是更好的方法,而不是使用库中没有的接口。

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.

考虑到这一点我想请任何人分享如何实现此方法的具体例子或链接(使用依赖注入来加载库实例上的每一个MVC请求)。

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).

推荐答案

DI背后的主要思想是迫使你看到大画面,而不是具体的实现。

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

您控制器需要获取用户,但它不应该关心具体的实现(贵存储库中取出从数据库,Web服务,XML文件等用户或不会使用LINQ2SQL,的EntityFramework,小巧玲珑什么否则引擎盖下)。

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).

您控制器是依赖于那块code可以在构造函数,属性或方​​法被注入,但它并没有真正关心具体的实现。

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删除您的控制器和存储库之间的紧耦合,允许你通过嘲讽库编写单元测试,你可以很容易改变的具体实施你的资料库中(如使用PetaPoco代替的EntityFramework)不接触的其余部分在code。

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.

您也应该看看SOLID原则:http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)

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