1

使用 Ninject DI,我实现了两个从 MVC 控制器实例化的接口。例如:

public class MyController : Controller
{
   private readonly IUnitOfWork _UnitOfWork;
   private readonly IAssetService _AssetService;

   public MyController(IUnitOfWork unitOfWork, IAssetService assetService)
   {
      this._UnitOfWork = unitOfWork;
      this._AssetService = assetService;
   }

   // Controller actions etc. 
}

在我的 Ninject 模块中,我创建了以下绑定:

public class DomainModule : NinjectModule
{
   public override void Load()
   {
      Bind<IUnitOfWork>()
         .To<SqlUnitOfWork>()
         .InRequestScope()
         .WithConstructorArgument("connectionString", "MyDb.Database");

      Bind<IAssetService>()
         .To<FileSystemAssetService>()
         .WithConstructorArgument("rootPath", "C:\\DataStore");
   }
}

我现在想将IUnitOfWork实例注入到我的IAssetService 中,所以我考虑将它作为一个属性IAssetService并修改我的控制器,如下所示:

public class MyController : Controller
{
   private readonly IUnitOfWork _UnitOfWork;
   private readonly IAssetService _AssetService;

   public MyController(IUnitOfWork unitOfWork, IAssetService assetService)
   {
      this._UnitOfWork = unitOfWork;
      this._AssetService = assetService;

      this._AssetService.UnitOfWork = this._UnitOfWork;
   }

   // Controller actions etc. 
}

但我想知道是否有更好/更清洁的方法使用不同的 DI 技术来执行此操作 - 理想情况下,我想将其添加IUnitOfWorkAssetService构造函数中?

4

1 回答 1

2

那为什么不简单地将IUnitOfWork注入AssetService

public class FileSystemAssetService : IAssetService
{
    private readonly IUnitOfWork unitOfWork;
    private readonly string rootPath;

    public FileSystemAssetService(IUnitOfWork unitOfWork, string rootPath)
    {
        this.unitOfWork = unitOfWork;
        this.rootPath = rootPath;
    }
}
于 2013-02-19T22:41:13.490 回答