我目前正在使用EF 6设置.NET Core应用程序,并且在理解各种依赖项注册方法的适当使用方面遇到了一些麻烦.据我了解:
特别是在我的情况下,我已经设置了一对DbContexts(基于CQRS模式)来处理我正在注册为Scoped的数据库查询/命令:
services.AddScoped((_) => new TestCommandContext(Configuration["Data:TestConnection:ConnectionString"]));
services.AddScoped((_) => new TestQueryContext(Configuration["Data:TestConnection:ConnectionString"]));
Run Code Online (Sandbox Code Playgroud)
这是根据ASP.NET 入门ASP.NET 5和Entity Framework 6文档:
每个范围应解决一次上下文,以确保性能并确保实体框架的可靠运行
我正在注册相应的UOW类:
services.AddTransient<ITestCommandUnit, TestCommandUnit>();
services.AddTransient<ITestQueryUnit, TestQueryUnit>();
Run Code Online (Sandbox Code Playgroud)
我基于这篇文章在这里使用Transient,这表明:
只要在应用程序中需要,就会创建在Transient范围注册的服务.这意味着每次执行(创建依赖项的方法)时,依赖注入框架将创建(注册服务)类的新实例.
基于这种理解,我正在使用Scoped注册我的存储库和服务类:
services.AddScoped<ITestCommandRepository, TestCommandRepository>();
services.AddScoped<ITestQueryRepository, TestQueryRepository>();
services.AddScoped<ITestCommandService, TestCommandService>();
services.AddScoped<ITestQueryService, TestQueryService>();
Run Code Online (Sandbox Code Playgroud)
然后根据需要在我的控制器中调用我各自的服务层方法:
public class TestController : BaseController
{
private ITestQueryService testQueryService;
// Get new object of type TestQueryService via DI
public TestController(ITestQueryService testQueryService)
{
this.testQueryService = testQueryService;
}
[HttpGet]
public IActionResult Edit(int …Run Code Online (Sandbox Code Playgroud) c# entity-framework dependency-injection unit-of-work asp.net-core