我的项目中有一个通用存储库。
考虑以下控制器片段
public class Lookup1Controller : Controller
{
readonly MyDbContext _db;
public Lookup1Controller(MyDbContext dataContext)
{
_db = dataContext;
}
public async Task<IActionResult> Index()
{
IGenericRepository<Lookup1> _repository = new GenericRepository<Lookup1>(_db);
var lookup1s = await _repository.SelectAll();
return View(lookup1s);
}
我认为不需要在我的通用存储库以及每个控制器中都包含我的数据库引用。
我将其重构为:
public class Lookup1Controller : Controller
{
private IGenericRepository<Lookup1> _repository;
public Lookup1Controller(IGenericRepository<Lookup1> repository)
{
_repository = repository;
}
public async Task<IActionResult> Index()
{
var lookup1s = await _repository.SelectAll();
return View(lookup1s);
}
}
从我读到的内容来看,这是更简洁的 ASP.NET 5 最佳实践。
但如果我在浏览器中访问该控制器路由,我会收到以下错误:
InvalidOperationException: Unable to resolve service for type 'MyProject.Data.IGenericRepository`1[MyProject.Models.Lookup1]' while attempting to activate 'MyProject.Controllers.Lookup1.
因为我还没有注入 GenericRepository 来使用该接口。
我添加到我的Startup.cs
an AddScoped
我的每个表的行ConfigureServices
method
services.AddScoped<IGenericRepository<Lookup1>,GenericRepository<Lookup1>> ();
services.AddScoped<IGenericRepository<Lookup2>,GenericRepository<Lookup2>> ();
services.AddScoped<IGenericRepository<Lookup3>,GenericRepository<Lookup3>> ();
services.AddScoped<IGenericRepository<Lookup4>,GenericRepository<Lookup4>> ();
etc
以便我的代码运行时不会引发异常。
然而我的数据库有大约 100 个简单的查找表。当我查看上面的 100 行代码时,我发现它看起来不太正确。
感觉就像复制并粘贴代码。每次我通过添加新模型和带有视图的控制器来添加新表时,我的代码都会编译而不会出现错误。但是,如果我运行程序并转到该视图,如果我忘记将 AddScoped 行添加到我的视图中,我可能会收到控制器运行错误。Startup.cs
。对于可维护性来说并不是很好。
我的问题:
为每个查找表提供 services.AddScoped 真的是最佳实践吗?ConfigureServices
的方法Startup.cs
?
它是一个通用存储库,所以是否有一种方法可以将这 100 行复制和粘贴行写在一行中?
如果不是,那么使用我的代码执行此操作的最佳实践方法是什么?