使用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技术这样做 - 理想情况下我想将IUnitOfWork
添加到AssetService
构造函数中?
答案 0 :(得分: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;
}
}