how to run specific service when dotnet core console starts

252 views Asked by At

In a .NET Core console app, I want to do this in Program.cs:

   public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseSerilog()
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.ConfigureServices(serviceCollection =>
                    {
                        serviceCollection.AddSingleton(new MyService()); // error on this line
                        
                    });
                    webBuilder.UseStartup<Startup>();
                });

The error I am getting is:

There is no argument given that corresponds to the required formal parameter 'logger' of 'MyService(ILogger, IMediator)'

And I am not sure how I am supposed to add the 2 required params (the serilog Logger and the mediat-r instances) when I call the constructor of MyService

I need this because the service must be called once when I open / run the console...

1

There are 1 answers

0
Sergey Nazarov On

You can use this code:

serviceCollection.AddSingleton(ctx => new MyService(ctx.GetService<ILogger>(), ctx.GetService<IMediator>()));

But it's not a good idea to inject instance of IMediator which have less lifetime period (I guess, because usually it's scoped) than your MyService.

Some info:

Do not depend on a transient or scoped service from a singleton service. Because the transient service becomes a singleton instance when a singleton service injects it and that may cause problems if the transient service is not designed to support such a scenario. ASP.NET Core’s default DI container already throws exceptions in such cases.