简体   繁体   中英

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.

Then the following error started happening but only when debugging in 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(); .

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:-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM