简体   繁体   English

环境特定错误:无法使用来自单例“Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor”的范围服务

[英]Environment specific error: Cannot consume scoped service from singleton 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor'

I have developed a .Net Core background service which was working fine both when running as a service and when debugging in Visual Studio.我开发了一个 .Net Core 后台服务,它在作为服务运行和在 Visual Studio 中调试时都运行良好。

Then the following error started happening but only when debugging in Visual Studio然后开始发生以下错误,但仅在 Visual Studio 中进行调试时

Cannot consume scoped service myDbContext from singleton 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor'"

On deployment the service does not experience the same problem.在部署时,服务不会遇到同样的问题。

I've read several posts saying to get around this by creating a scoped service, however if I set the project up on a different machine by getting the code from source control, the error doesn't happen .我读过几篇文章说通过创建范围服务来解决这个问题,但是如果我通过从源代码管理中获取代码将项目设置在不同的机器上,则不会发生错误

I have deleted the project from the problem environment and pulled the code from source control again but the issue still arises.我已经从问题环境中删除了该项目,并再次从源代码管理中提取了代码,但问题仍然出现。

To me this suggests it's an environment issue, rather than a coding one.对我来说,这表明这是一个环境问题,而不是编码问题。

The basic code is below.基本代码如下。

The issue arises at the line host.Run();问题出现在行host.Run(); . .

Does anyone have any pointers as to how to isolate the cause and therefore potentially find a fix?有没有人有任何关于如何隔离原因并因此可能找到解决方法的指示?

Thanks谢谢

    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));
        }
    }

异常如何表现自己的屏幕截图

I have been working in dotnet core since 2 years and things that i found out is:-我已经在 dotnet core 工作了 2 年,我发现的事情是:-

Do not resolve a scoped service from a singleton.不要从单例解析范围服务。 It may cause the service to have incorrect state when processing subsequent requests.可能会导致服务在处理后续请求时状态不正确。 It's fine to:没问题:

Resolve a singleton service from a scoped or transient service.从作用域或瞬态服务解析单例服务。 Resolve a scoped service from another scoped or transient service.从另一个范围服务或瞬态服务解析范围服务。 By default, in the development environment, resolving a service from another service with a longer lifetime throws an exception.默认情况下,在开发环境中,从另一个生命周期较长的服务解析服务会引发异常。 For more information, Scope Validation有关更多信息, 范围验证

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用来自单例“Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor”的范围服务“MyDbContext” - Cannot consume scoped service 'MyDbContext' from singleton 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor' 无法使用单例的作用域服务 - Cannot consume scoped service from singleton 无法从根提供程序解析范围服务Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.IViewBufferScope - Cannot resolve scoped service Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.IViewBufferScope from root provider 无法使用来自单例 Windows 主机服务的范围服务 - Cannot consume scoped service from singleton Windows Host Service InvalidOperationException:无法从 Blazor 中的单例“...IAuthentication”使用范围服务“Microsoft.JSInterop.IJSRuntime” - InvalidOperationException: Cannot consume scoped service 'Microsoft.JSInterop.IJSRuntime' from singleton '...IAuthentication' in Blazor 无法从单例yyy中使用作用域服务xxx - Cannot consume scoped service xxx from singleton yyy 不能从singleton中使用作用域服务MyDbContext - InvalidOperationException - Cannot consume scoped service MyDbContext from singleton - InvalidOperationException MultiTenant自定义ILogger - 不能从单例中使用作用域服务 - MultiTenant custom ILogger - cannot consume scoped service from singleton 无法使用来自单例“IMyCustomThing”的范围服务“IHttpContextAccessor” - Cannot consume scoped service 'IHttpContextAccessor' from singleton 'IMyCustomThing' .NET 核心 DI:无法使用来自 singleton 的范围服务 - .NET Core DI: Cannot consume scoped service from singleton
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM