我正在使用 .Net Core 后台服务连接到 Kafka 并将消息保存到 SQL Server。我的项目结构如下所示:
在基础设施依赖项中,我有以下代码来使用从 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/