小编Ben*_*ers的帖子

.NET Core/EF 6 - 依赖注入范围

我目前正在使用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

11
推荐指数
2
解决办法
4131
查看次数