相关疑难解决方法(0)

我应该如何将一个DbContext实例注入IHostedService?

我应该如何将一个DbContext实例注入(使用标准依赖注入)IHostedService

我试过了什么

我目前让我的IHostedServiceMainContextDbContext构造函数中获取(派生自)实例.

当我运行应用程序时,我得到:

无法从singleton'Microsoft.Extensions.Hosting.IHostedService'中使用作用域服务"Microsoft.EntityFrameworkCore.DbContextOptions".

所以我试着DbContextOptions通过指定来制作瞬态:

services.AddDbContext<MainContext>(options => 
                options.UseSqlite("Data Source=development.db"), ServiceLifetime.Transient);
Run Code Online (Sandbox Code Playgroud)

在我Startup班上

但是错误仍然是相同的,即使根据这个解决的Github问题,DbContextOptions传递的应该具有在AddDbContext调用中指定的相同生命周期.

我无法使数据库上下文成为单例,否则对它的并发调用将产生并发异常(由于数据库上下文不保证是线程安全的事实).

.net c# asp.net .net-core asp.net-core

36
推荐指数
2
解决办法
1万
查看次数

如何解决无法使用范围服务

我已将托管服务添加到我的 .net core 3.1 项目中。但添加托管服务后我面临以下错误。

无法使用范围服务

。在此之前我的项目运行良好。我想为我的项目添加后台服务从数据库获取数据。

启动.cs

services.AddScoped<IScheduleService, ScheduleService>();
services.AddHostedService<TimedHostedService>();
Run Code Online (Sandbox Code Playgroud)

SMhostedService.cs

internal class TimedHostedService : IHostedService, IDisposable
    {
        private readonly Microsoft.Extensions.Logging.ILogger _logger;
        private Timer _timer;
        private IScheduleService _scheduleService;
        public TimedHostedService(ILogger<TimedHostedService> logger, IScheduleService scheduleService)
        {
            _logger = logger;
            _scheduleService = scheduleService;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Timed Background Service is starting.");

            _timer = new Timer(DoWork, null, TimeSpan.Zero,
                TimeSpan.FromSeconds(10));

            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            _logger.LogInformation("Timed Background Service is working.");
            DateTime todaydate = new DateTime();
            var getAttendanceStatus = …
Run Code Online (Sandbox Code Playgroud)

c# .net-core asp.net-core-3.1

5
推荐指数
1
解决办法
4049
查看次数

标签 统计

.net-core ×2

c# ×2

.net ×1

asp.net ×1

asp.net-core ×1

asp.net-core-3.1 ×1