c# - 无法从单例 'ApplicationDbContext' 消耗作用域服务 'Microsoft.Extensions.Hosting.IHostedService'

标签 c# .net-core entity-framework-core ihostedservice

我正在使用 .Net Core 后台服务连接到 Kafka 并将消息保存到 SQL Server。我的项目结构如下所示: enter image description here

在基础设施依赖项中,我有以下代码来使用从 Worker 的 Program.cs 文件传递​​的 IConfiguration 配置 注册 Entity Framework,即 services.AddInfrastruct(配置);

namespace JS.Svf.BackgroundServices.Infrastructure
{
    public static class DependencyInjection
    {
        public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
        {
            // Add all the dependencies required by Azure Functions.
            // From Infrastructure

            services.AddDbContext<ApplicationDbContext>(options =>
                       options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"),
                           b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)));

            services.AddTransient<IApplicationDbContext>(provider => provider.GetRequiredService<ApplicationDbContext>());
            services.AddTransient<IProductRepository, ProductRepository>();
            services.AddTransient<ISupplierRepository, SupplierRepository>();
            return services;
        }
    }
}

运行后台服务后出现以下错误: 无法使用单例“Microsoft.Extensions.Hosting.IHostedService”中的作用域服务“ApplicationDbContext”

通过引用,我知道我们需要使用 IServiceScopeFactory 但我对如何在当前结构中使用它有点无能为力。请指教。

存储库使用ApplicationDbContext。这里如何使用IServiceScopeFactory

namespace JS.Svf.Functions.Infrastructure.Persistence
{
    public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        protected readonly ApplicationDbContext _context;

        public Repository(ApplicationDbContext context)
        {
            _context = context;
        }

        public void Add(TEntity entity)
        {
            _context.Set<TEntity>().Add(entity);
            _context.SaveChanges();
        }
    }
}

最佳答案

在您的单例服务 IHostedService 中,将 IServiceScopeFactory 注入(inject)其中,并使用它来创建范围并从中获取新的 DbContext它。例如:

public class MyHostedService : IHostedService
{
    private readonly IServiceScopeFactory _scopeFactory;

    public MyHostedService(IServiceScopeFactory scopeFactory)
    {
        // Inject the scope factory
        _scopeFactory = scopeFactory;
    }

    private async Task SomeMethodThatNeedsTheContext()
    {
        // Create a new scope (since DbContext is scoped by default)
        using var scope = _scopeFactory.CreateScope();

        // Get a Dbcontext from the scope
        var context = scope.ServiceProvider
            .GetRequiredService<ApplicationDbContext>();           

        // Run a query on your context
        var quadrupeds = await context.Animals
            .Where(a => a.Legs == 4)
            .ToListAsync();
    }
}

关于c# - 无法从单例 'ApplicationDbContext' 消耗作用域服务 'Microsoft.Extensions.Hosting.IHostedService',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72113872/

相关文章:

entity-framework-core - 使用接口(interface)搭建 EF Core 实体

c# - 如何制作具有 Action 范围的开/关门?

c# - 拒绝对 DataRow 中单个 DataColumn 的更改

c# - 删除 Entity Framework Core 查询中重复的 SUM 子查询

.net-core - dotnet build 如何选择输出名称

asp.net-core - .net core本地开发的项目组织

c# - 如何让 EF Core 数据库首先使用枚举?

c# - DateTime.ParseExact() 不理解 24 小时时间值吗?

c# - 文件访问和资源管理器窗口的奇怪异常

c# - 在 Xcode 中创建 C/C++ 库并将其导入到 C# .NET Core 中