![](/img/trans.png)
[英]Cannot consume scoped service 'MyDbContext' from singleton 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor'
[英]Environment specific error: Cannot consume scoped service from singleton 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor'
我開發了一個 .Net Core 后台服務,它在作為服務運行和在 Visual Studio 中調試時都運行良好。
然后開始發生以下錯誤,但僅在 Visual Studio 中進行調試時
Cannot consume scoped service myDbContext from singleton 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor'"
在部署時,服務不會遇到同樣的問題。
我讀過幾篇文章說通過創建范圍服務來解決這個問題,但是如果我通過從源代碼管理中獲取代碼將項目設置在不同的機器上,則不會發生錯誤。
我已經從問題環境中刪除了該項目,並再次從源代碼管理中提取了代碼,但問題仍然出現。
對我來說,這表明這是一個環境問題,而不是編碼問題。
基本代碼如下。
問題出現在行host.Run();
.
有沒有人有任何關於如何隔離原因並因此可能找到解決方法的指示?
謝謝
public class Program
{
public static void Main(string[] args)
{
var method = MethodBase.GetCurrentMethod();
var methodName = method.Name;
var type = method.DeclaringType;
Log.Information("{0}.{1}: Started.", type, methodName);
try
{
var isService = !(Debugger.IsAttached || args.Contains("--console"));
if (isService)
{
var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);
Directory.SetCurrentDirectory(pathToContentRoot);
}
var builder = CreateWebHostBuilder(args.Where(arg => arg != "--console").ToArray());
var host = builder.Build();
if (isService)
{
host.RunAsWebCustomService();
}
else
{
host.Run();
}
return;
}
catch (Exception ex)
{
Log.Fatal(ex, "Error in {0{.{1}: {2}", type, methodName, ex.Message);
throw;
}
finally
{
Log.CloseAndFlush();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
var method = MethodBase.GetCurrentMethod();
var methodName = method.Name;
var type = method.DeclaringType;
Log.Information("{0}.{1}:called", type, methodName);
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(AppContext.BaseDirectory))
.AddJsonFile("appsettings.json", optional: true);
var configuration = builder.Build();
var url = configuration["WebHostBuilder:Url"];
return WebHost.CreateDefaultBuilder(args)
.UseUrls(url)
.ConfigureServices(
(hostContext, services) =>{services.AddHostedService<Worker>();})
.UseStartup<Startup>()
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration));
}
}
我已經在 dotnet core 工作了 2 年,我發現的事情是:-
不要從單例解析范圍服務。 可能會導致服務在處理后續請求時狀態不正確。 沒問題:
從作用域或瞬態服務解析單例服務。 從另一個范圍服務或瞬態服務解析范圍服務。 默認情況下,在開發環境中,從另一個生命周期較長的服務解析服務會引發異常。 有關更多信息, 范圍驗證
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.