这是我的
program.cs
:
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton<cMain>();
// Ensure cMain is constructed before using it to get the connection string
var serviceProvider = builder.Services.BuildServiceProvider();
var cMainInstance = serviceProvider.GetRequiredService<cMain>();
var connectionString = cMainInstance.ConnectionString;
// Register the DbContext with the correct connection string
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddHostedService<Worker>();
var host = builder.Build();
host.Run();
这是我的
UnitOfWork
和IUnitOfWork
:
public class UnitOfWork : IUnitOfWork
{
private readonly ApplicationDbContext _db;
public UnitOfWork(ApplicationDbContext db)
{
_db = db;
BreadCrumbs = new BreadCrumbRepository(_db);
}
public IBreadCrumbRepository BreadCrumbs { get; private set; }
public void Save()
{
_db.SaveChanges();
}
}
public interface IUnitOfWork
{
IBreadCrumbRepository BreadCrumbs { get; }
void Save();
}
我正在尝试将
IUnitOfWork
注入到工作线程中,但出现以下错误:
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly cMain _cmain;
private readonly IConfiguration _configuration;
private readonly IUnitOfWork _uow;
public Worker()
{
}
public Worker(ILogger<Worker> logger, IConfiguration configuration, IUnitOfWork uow)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_uow = uow ?? throw new ArgumentNullException(nameof(uow));
_cmain = new cMain(_configuration);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var breadCrumb = new BreadCrumb
{
Application = Assembly.GetExecutingAssembly().GetName().Name,
DateTime = DateTime.Now,
Description = "Test",
EnquiryHeader_ID = 1,
EventName = "Test",
ReferenceID = 1,
Result = "Test"
};
//await _uow.BreadCrumbs.AddAsync(breadCrumb);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
}
await Task.Delay(1000, stoppingToken);
}
}
}
我得到的错误如下
抛出异常:Microsoft.Extensions.DependencyInjection.dll 中的“System.AggregateException”
部分服务无法构建如果有此异常的处理程序,则程序可以安全地继续。
我真的很感激你指出我哪里出了问题或我遗漏了什么
我期望应用程序能够运行并消耗工作者类中的
IUnitOfWork
。当我删除 DI 时,它会运行。
问题在于该服务已注册为范围
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
它需要是后台工作者的单例。
如果您需要将生命周期限定为 UnitOfWork 的范围,请在此处阅读有关如何在工作线程中创建范围的信息。 https://learn.microsoft.com/en-us/dotnet/core/extensions/scoped-service