如何实现多个

How to implement multiple

我添加了存储库代码并将其调用到 HomeController.cs

 public class HomeController : Controller
 {
     private IPlatformRepository _platformRepository;

     public HomeController()
     {
         this._platformRepository = new PlatformRepository(new IoTSimulatordbContext());    
     }

     public HomeController(IPlatformRepository platformRepository )
     {
         this._platformRepository = platformRepository;    
     }

以上代码仅适用于 PlatformRepository 如果我想添加多个存储库,我可以像下面那样做吗?

 public class HomeController : Controller
 {
     private IPlatformRepository _platformRepository;
     private IDeviceRepository _deviceRepository;

     public HomeController()
     {
         this._platformRepository = new PlatformRepository(new IoTSimulatordbContext());
         this._deviceRepository = new DeviceRepository(new IoTSimulatordbContext());
     }

     public HomeController(IPlatformRepository platformRepository, IDeviceRepository deviceRepository)
     {
         this._platformRepository = platformRepository;
         this._deviceRepository = deviceRepository;

     }

这是正确的做法吗?

public HomeController()
{
    this._platformRepository = new PlatformRepository(new IoTSimulatordbContext());

    this._deviceRepository = new DeviceRepository(new IoTSimulatordbContext());
}

是的,两次实例化IoTSimulatordbContext就可以了。如果你的应用程序变得更大,你可能会得到一些错误,因为同一个实例在多个地方使用而不是线程节省。此外,以这种方式管理实例化需要您正确管理实例的处置。

我建议您使用依赖注入(使用 Autofac 或 Ninject)- 它将帮助您管理 class 实例化并处理它们。所以你的 DI 构造函数看起来像这样

public class HomeController : Controller
 {
     private readonly IPlatformRepository _platformRepository;
     private readonly IDeviceRepository _deviceRepository;


     public HomeController(IPlatformRepository platformRepository, IDeviceRepository deviceRepository)
     {
         this._platformRepository = platformRepository;
         this._deviceRepository = deviceRepository;

     }

如果你问的是语法,那么我看不出有什么问题...如果你问的是设计和最佳实践,那么请考虑以下几点:

  1. 最好将存储库注入控制器,因为初始化存储库与控制器无关...您的代码违反了单一职责原则,因为控制器有 extra/unnecessary 初始化存储库的责任。

  2. 您问题中的另一个要点是关于控制器中依赖项的数量。为此,我建议您参考 Nikola 的 IoC 第二定律see here

Any class having more then 3 dependencies should be questioned for SRP violation

您的控制器依赖于 2 个存储库,所以它很好...但是如果您有超过 3 个依赖项,最好考虑重构。如果您想知道如何重构存储库,请考虑以下内容:

  • 确定您的域的 Aggregate roots 并为每个聚合根创建一个存储库...所以本质上您是在一个存储库中组合相关类型。

  • 您可以将存储库组合成一个更大的块(服务)...现在高级 class(控制器)依赖于您的服务,而服务又依赖于一个或多个存储库。