ASP.Net MVC:使用多个存储库并通过 Unity DI 注入

ASP.Net MVC: working with multiple repositories & injection by Unity DI

我正在使用 asp.net mvc 5 项目。假设我在显示客户详细信息和客户最喜欢的产品的位置显示客户数据。

所以我从客户资料库、国家资料库和最喜欢的资料库中获取数据。

很多时候人们通过 unity DI 写关于注入库的文章。当我使用单个存储库时,这个概念很有意义,但是当我必须从多个存储库中获取数据时,我如何通过 unity di 在 mvc 控制器 ctor 中注入多个存储库?

查看unity DI注入仓库的小代码

public class FooController : Controller  
{  
     readonly IFooRepository _repository;  

     // Inject here  
     public ProductController(IFooRepository repository)  
     {  
           _repository = repository;   
     }  

     // Use it here  
     public ActionResult Bar()  
     {  
          var bar = _repository.DoSomething();  
     }  
}  

以上代码参考自https://forums.asp.net/t/2105895.aspx?Repository+inject+into+controller+by+Unity+DI

现在告诉我如何重构我的代码或我应该遵循什么方法以便我可以使用多个存储库并且还可以通过 Unity DI 注入。

请给我最好的指导。谢谢

只需将您需要的任何依赖项添加到控制器的构造函数中即可。

public class FooController : Controller  
{  
    readonly IFooRepository _repository;  
    readonly IOtherRepository _otherRepository;  

    public ProductController(IFooRepository repository, IOtherRepository otherRepository)  
    {  
        _repository = repository;   
        _otherRepository = otherRepository;
    }  

请注意,虽然 L-Four 通常是一个不错的选择,但稍后您可能 运行 遇到困难对加载的实体进行了一些修改并希望保存它们,因为您可能最终在存储库中拥有单独的 DBContext 实例。但这取决于您的存储库和 DI 实现和配置...

示例:

// Assume you want to create a new User with associated Account

var user = _usersRepository.AddUser(new User(....));
var account = _accountRepository.AddAccount(new Account{ ... User = user });

// Now you want to save them both in one transaction... how?
_usersRepository.Commit();
_accountRepository.Commit(); // What if this fails? you have an orphaned user?

为了解决这个问题,我建议实施所谓的 Unit Of Work 模式。还有一些good examples also on Stack Overflow and elsewhere.

可能会让你以后不再头疼。

您更新后的代码将是:

public class FooController : Controller  
{  
     readonly IUsersAndAccountUnitOfWork _uow;  

     // Inject here  
     public ProductController(IUsersAndAccountUnitOfWork uow)  
     {  
           _uow = uow;
     }  

     // Use it here  
     public ActionResult Bar()  
     {  
           var user = _uow.Users.AddUser(new User(....));
           var account = _uow.Accounts.AddAccount(new Account{ ... User = user });

           _uow.Commit();
     }  
}