Is It possible to inject dependencies after winservice starts?

166 Views Asked by At

I have ASP.NET Core 3.1 WebAPI that can be started as winservice.

public class Program
{
    public static async Task Main(string[] args)
    {
        IHostBuilder builder = CreateHostBuilder(args);

        if (isService)
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
            var pathToContentRoot = Path.GetDirectoryName(pathToExe);
            builder.UseContentRoot(pathToContentRoot);
            builder.ConfigureServices((hostContext, services) => services.AddSingleton<IHostLifetime, ServiceBaseLifetime>());
        }

        var host = builder.Build();

        if (isService)
        {
            await host.RunAsync();
        }
        else
        {
            host.Run();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
             .ConfigureWebHostDefaults(webBuilder =>
             {
                 webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
                 webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
                 {
                     var env = hostingContext.HostingEnvironment;
                     config.AddEnvironmentVariables();
                     if (args != null)
                     {
                         config.AddCommandLine(args);
                     }
                 });
                 webBuilder.UseStartup<Startup>();
                 webBuilder.UseKestrel(options =>
                 {
                     options.Listen(IPAddress.Parse("0.0.0.0"), port, listenOptions =>
                     {
                         listenOptions.UseHttps("cert.pfx", "password");
                     });
                 });
             });
    }
}

To start it as winservice ServiceBaseLifetime class is used. It has methods OnStart, OnStop (from IHostLifetime).

Service is started after all injections in Startup.cs are finished. But I have one long-running operation in Startup.cs which result determines which dependencies to inject. Because of it sometimes winservice starts for a very long time, and I get a timeout error. I can increase the timeout by adding ServicesPipeTimeout to the registry, it works. But I want to solve this issue another way.

Is it possible to start windows service and then perform long-running operation and after it completes inject needed dependencies outside the Startup?

0

There are 0 best solutions below