无法在存储库中注入 DbContext

Cannot inject DbContext in repository

我尝试为新的 ASP.NET 核心站点设置 DI,我有以下代码:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // Get the configuration from the app settings.
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();

    // Get app settings to configure things accordingly.
    var appSettings = Configuration.GetSection("AppSettings");
    var settings = new AppSettings();
    appSettings.Bind(settings);

    services
        .AddOptions()
        .Configure<AppSettings>(appSettings)
        .AddSingleton<IConfigurationRoot>(config)
        .AddDbContext<MyDbContext>(builder =>
        {
            builder.UseSqlServer(config.GetConnectionString("myConn"));
        }, ServiceLifetime.Transient, ServiceLifetime.Transient);

    services.AddSingleton<ILoadTestCleanUpServiceRepository, LoadTestCleanUpServiceRepository>();
        ...

现在,LoadTestCleanUpServiceRepository 取决于 MyDbContext:

public class LoadTestCleanUpServiceRepository : ILoadTestCleanUpServiceRepository
{
    private readonly MyDbContext _dbContext;

    public LoadTestCleanUpServiceRepository(MyDbContext dbContext)
    {
        _dbContext = dbContext;
    }
    ...

..数据库上下文是这样的:

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> ctxOptions) : base(ctxOptions)
    {
    }
}

当我 运行 应用程序时,出现此错误:

InvalidOperationException: Unable to resolve service for type 'MyCode.Infrastructure.Common.MyDbContext' while attempting to activate 'MyCode.Infrastructure.LoadTestCleanUpService.LoadTestCleanUpServiceRepository'.

我尝试更改 ServiceLifetime 选项并添加以下额外代码:

services.AddTransient<MyDbContext>(sp => new MyDbContext(config));

...但似乎没有任何帮助,我不明白为什么这不起作用。它确实尝试构建存储库,但为什么它不能也构建数据库上下文?连我叫UseSqlServer()的地步都没有! 有什么想法吗?

更新 1:

嗯...我现在看到了。很可能是相关的:

更新 2:

我现在有:

但我仍然得到同样的错误。

我看到您已将 LoadTestCleanUpServiceRepository 注册为 Singleton,而将 MyDbContext 注册为 Transient,然后您正尝试从 [=11= 解析 MyDbContext ].那就是问题所在。根据 ASP.NET Core Service lifetimes 文档:

It's dangerous to resolve a scoped service/transient service from a singleton. It may cause the service to have incorrect state when processing subsequent requests.

解决方法是:注册LoadTestCleanUpServiceRepositoryMyDbContext如下:

services.AddDbContext<MyDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("YourConnectionStringName")));

services.AddScoped<ILoadTestCleanUpServiceRepository, LoadTestCleanUpServiceRepository>();

现在问题应该消失了。