Click here to Skip to main content
15,881,089 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Hi
I am working on worker service asp.net core 3.0 .
I am getting the following error:
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: WindowsService.Worker': Cannot consume scoped service 'WindowsService.Models.MotherLoadContext' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.)
Source=Microsoft.Extensions.DependencyInjection

Inner Exception 1:
InvalidOperationException: Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: WindowsService.Worker': Cannot consume scoped service 'WindowsService.Models.DBContext' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.

Inner Exception 2:
InvalidOperationException: Cannot consume scoped service 'WindowsService.Models.DBContext' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.


How do i resolve this issue

Following is my code:

This my code snippet:

<pre>public static void Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();
            CreateHostBuilder(args).Build().Run();
            
        }

     

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    

                    services.AddDbContext<MotherLoadContext>(options => options.UseSqlServer(ConfigurationManager.ConnectionStrings["MotherLoadConnStr"].ConnectionString));

                    IConfiguration configuration = hostContext.Configuration;
                    ShopifyConfigSettings configSettings = configuration.GetSection("ShopifyWebService").Get<ShopifyConfigSettings>();
        
                    });
                    services.AddSingleton(configSettings);
                    services.AddHostedService<Worker>();
                    services.AddLogging();
                   



                 

                });


What I have tried:

This my code snippet:

public static void Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();
            CreateHostBuilder(args).Build().Run();
            
        }

     

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    

                    services.AddDbContext<MotherLoadContext>(options => options.UseSqlServer(ConfigurationManager.ConnectionStrings["MotherLoadConnStr"].ConnectionString));

                    IConfiguration configuration = hostContext.Configuration;
                    ShopifyConfigSettings configSettings = configuration.GetSection("ShopifyWebService").Get<ShopifyConfigSettings>();
        
                    });
                    services.AddSingleton(configSettings);
                    services.AddHostedService<Worker>();
                    services.AddLogging();
                   
                });
Posted
Updated 5-Dec-19 2:37am

1 solution

Hosted services are registered as singletons, and cannot directly depend on scoped services. If an instance of a scoped services was injected into a singleton service, it would become a singleton itself.

Captive Dependency[^]
The dangers and gotchas of using scoped services in IConfigureOptions[^]

Your Worker class (which you haven't shown) takes a direct dependency on a scoped service - presumably the Entity Framework context.

The documentation has an example of working around this limitation:
Background tasks with hosted services in ASP.NET Core | Microsoft Docs[^]

Essentially, you inject an IServiceScopeFactory into your singleton service. When you need a scoped service, you create a scope and resolve the service from that:
C#
public class MySingletonService
{
    private IServiceScopeFactory Services { get; }
    
    public MySingletonService(IServiceScopeFactory services)
    {
        Services = services;
    }
    
    public void DoSomethingWithScopedService()
    {
        using (var scope = Services.CreateScope())
        {
            var myScopedService = scope.GetRequiredService<IScopedService>();
            // ... Use the service here ...
        }
    }
}
(The Microsoft example injects IServiceProvider, but IServiceScopeFactory is more appropriate, since you only need the CreateScope method.)

NB: This is not pure "DI", because the dependencies of the singleton service are hidden within the implementation. Some people will call this the "service locator anti-pattern". But as far as I can see, it's about your only option for using a scoped service from a singleton.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900