验证服务描述符服务型时类型时,工人服务错误

发布于 2025-01-28 04:52:39 字数 2134 浏览 2 评论 0原文

我有一个在.NET Core 3.1中写的工人服务。在这里,我想在我的program.cs中在另一层(icarverticallogic和iemailpdflogic)中注册服务,但是当我运行项目时,我会收到以下错误。

我的program.cs

 public class Program
    {
        public static void Main(string[] args)
        {
            var startupPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule?.FileName);
            var logFilePath = Path.Combine(startupPath, "logs", "logs.txt");

            Log.Logger = new LoggerConfiguration()
                .WriteTo.File(logFilePath, rollingInterval: RollingInterval.Day)
                .CreateLogger();

            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
             Host.CreateDefaultBuilder(args)
                 .UseWindowsService()
                 .ConfigureLogging(logging =>
                 {
                     logging.AddSerilog();
                 })
                 .ConfigureServices((hostContext, services) =>
                 {
                     services.AddSingleton(AutoMapperConfig.CreateMapper());
                     services.AddScoped<ICarVerticalLogic, CarVerticalLogic>();
                     services.AddScoped<IEmailPdfLogic, EmailPdfLogic>();
                     services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));

                     services.AddEntityFrameworkSqlServer()
                     .AddDbContext<AsamDbContext>(options =>
                     {
                         options.UseMySql(hostContext.Configuration.GetSection("ConnectionString").Value);
                     });
                     services.AddHostedService<Worker>();
                 });
    }

错误:

InvalidOperationException: Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: CarVerticalWorkerService.Worker': Cannot consume scoped service 'Asam.Logic.Infrastructure.ICarVerticalLogic' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.

I have a worker service that I wrote in .Net Core 3.1. Here I want to register services in another layer (ICarVerticalLogic and IEmailPdfLogic) in my program.cs, but when I run the project I get the following error.

My Program.cs

 public class Program
    {
        public static void Main(string[] args)
        {
            var startupPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule?.FileName);
            var logFilePath = Path.Combine(startupPath, "logs", "logs.txt");

            Log.Logger = new LoggerConfiguration()
                .WriteTo.File(logFilePath, rollingInterval: RollingInterval.Day)
                .CreateLogger();

            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
             Host.CreateDefaultBuilder(args)
                 .UseWindowsService()
                 .ConfigureLogging(logging =>
                 {
                     logging.AddSerilog();
                 })
                 .ConfigureServices((hostContext, services) =>
                 {
                     services.AddSingleton(AutoMapperConfig.CreateMapper());
                     services.AddScoped<ICarVerticalLogic, CarVerticalLogic>();
                     services.AddScoped<IEmailPdfLogic, EmailPdfLogic>();
                     services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));

                     services.AddEntityFrameworkSqlServer()
                     .AddDbContext<AsamDbContext>(options =>
                     {
                         options.UseMySql(hostContext.Configuration.GetSection("ConnectionString").Value);
                     });
                     services.AddHostedService<Worker>();
                 });
    }

Error :

InvalidOperationException: Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: CarVerticalWorkerService.Worker': Cannot consume scoped service 'Asam.Logic.Infrastructure.ICarVerticalLogic' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浪荡不羁 2025-02-04 04:52:39

默认情况下,工人服务是单身服务。并且范围的服务实例注定要请求。您无法将范围的服务注入Singleton服务。

如果您不介意改变icarverticallogic和iemailpdflogic服务的寿命
对于Singleton,请尝试修改您的代码:

services.AddScoped<ICarVerticalLogic, CarVerticalLogic>();
services.AddScoped<IEmailPdfLogic, EmailPdfLogic>();

services.AddSingleton<ICarVerticalLogic, CarVerticalLogic>();
services.AddSingleton<IEmailPdfLogic, EmailPdfLogic>();

我的测试结果:

The worker service is a singleton service by default. And a scoped service instances are bound to request. You can not inject a scoped service into a singleton service.

If you don't mind change the lifetime of ICarVerticalLogic and IEmailPdfLogic service
to Singleton, try to modify your codes:

services.AddScoped<ICarVerticalLogic, CarVerticalLogic>();
services.AddScoped<IEmailPdfLogic, EmailPdfLogic>();

to

services.AddSingleton<ICarVerticalLogic, CarVerticalLogic>();
services.AddSingleton<IEmailPdfLogic, EmailPdfLogic>();

And here's my test result:
enter image description here

知足的幸福 2025-02-04 04:52:39

或者,对于Ruikai答案,您可以将服务提供商注入构造函数:

IServiceProvider _serviceProvider

然后创建一个范围。在Singleton中注入范围的服务:

using var scope = _serviceProvider.CreateScope();
var carService = scope.ServiceProvider.GetRequiredService<ICarVerticalLogic>();

Alternatively to Ruikai answer you can inject the service provider in the constructor:

IServiceProvider _serviceProvider

Then create a scope. To inject the scoped service in the singleton:

using var scope = _serviceProvider.CreateScope();
var carService = scope.ServiceProvider.GetRequiredService<ICarVerticalLogic>();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文