Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将DBContext服务添加到Worker项目中的program.cs_C#_Sql Server_Entity Framework Core - Fatal编程技术网

C# 将DBContext服务添加到Worker项目中的program.cs

C# 将DBContext服务添加到Worker项目中的program.cs,c#,sql-server,entity-framework-core,C#,Sql Server,Entity Framework Core,我对这一切都很陌生,所以如果我做了什么蠢事,我向你道歉 我正在尝试实现一个worker项目,并与已设置的本地SQL Server Express数据库进行通信 我将连接字符串存储在我的AppSettings.Json中,如下所示 { "Logging": { "LogLevel": { "Default": "Information", "Microsoft":

我对这一切都很陌生,所以如果我做了什么蠢事,我向你道歉

我正在尝试实现一个worker项目,并与已设置的本地SQL Server Express数据库进行通信

我将连接字符串存储在我的
AppSettings.Json
中,如下所示

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "DBConnection": "Server=localhost\\SQLEXPRESS;Database=TwitterTesting;Trusted_Connection=True;"
  }
}
然后我有一个
DBContext.cs
文件,它存储了我的数据库结构。目前我只有一张“tweets”表格

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkerService1.Entities;

namespace WorkerService1
{
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions options) : base(options)
        {
        }

        public DbSet<tweets> tweets { get; set; }
    }
}
上面是我的
program.cs
文件,我试图在其中添加
DBContext
的实现,但编译时出现以下错误:

System.AggregateException:'无法构造某些服务(验证服务描述符“ServiceType:Microsoft.Extensions.Hosting.IHostedService生存期:Singleton实现类型:WorkerService1.Worker”时出错:无法使用Singleton“Microsoft.Extensions.Hosting.IHostedService”中的作用域服务“WorkerService1.DataContext”。)

我从网上了解到这与依赖注入有关,但我真的对我需要做什么感到困惑


任何帮助都将不胜感激!:)

问题是您正试图创建DbContext的
范围
服务,但将要使用它的类(
Worker
)是一个
单例
类-请注意以下两行

services.AddDbContextPool<DataContext>( /*omitted*/ );
services.AddHostedService<Worker>();

有关更多信息,请查看下一页-尤其要注意“作用域”、“瞬态”和“单例”。

问题在于,您试图创建DbContext的
范围
服务,但将要使用它的类(
Worker
)是一个
Singleton
类-请注意以下两行

services.AddDbContextPool<DataContext>( /*omitted*/ );
services.AddHostedService<Worker>();

有关更多信息,请查看下一页-尤其要注意“作用域”、“瞬态”和“单例”。

您在哪里定义WorkerService1.DataContext以及如何将其添加到DI?@Saeedesmaelinejad抱歉,我不太清楚您的意思?您在哪里定义WorkerService1.DataContext以及如何将其添加到DI?@Saeedesmaelinejad抱歉,我不太清楚您的意思?
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Options;
using System;
using System.Threading;
using System.Threading.Tasks;
private readonly ILogger<Worker> _logger;
private readonly IServiceProvider _serviceProvider;

public Worker (ILogger<Worker> logger, IServiceProvider serviceProvider)
{
    _logger = logger;
    _serviceProvider = serviceProvider;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        _logger.Log("Creating scope to get a new DataContext.");
        // this will give us a scoped service
        var scope = _serviceProvider.CreateScope().ServiceProvider;
        // if DataContext were configured as singleton through AddSingleton<DataContext> 
        // in ConfigureServices, this would always be the same instance. Since it's added 
        // as Scoped, we'll get the same instance every time we ask for the service from 
        // our scope but each time we create a new scope it'll be a new instance.
        var context = scope.GetService<DataContext>();
        // do something with context
        // we can validate that within our scope it's always the same object reference:
        _logger.Log("Get scoped service multiple times yields the same reference: {0}", object.ReferenceEquals(context, scope.GetService<DataContext>());
        context.Dispose();
    }
}