YMC
YMC

Reputation: 5462

Need to access instance of service inside HostBuilder configured inside the same HostBuilder().ConfigureServices

Is it possible to access instance of DI configured services inside HostBuilder() configuration?

here is what I meant:

return new HostBuilder()
    .UseOrleans((cntx, builder) =>
    {
        builder.ConfigureApplicationParts(parts =>
        {
            // This is where I want to access instance of IMyService
            // in order to help Orleans builder to configure Orleans properly
        }
    })
    .ConfigureServices(services =>
    {
        services.AddSingleton<IMyService, MyService>();
    })
    .RunConsoleAsync();

Upvotes: 5

Views: 3612

Answers (1)

Nkosi
Nkosi

Reputation: 247591

In case this turns out to be an XY problem, and you are you trying to create some startup task, there is a AddStartupTask extension

return new HostBuilder()
    .UseOrleans((cntx, builder) => {            
        //Add a startup task to be executed when the silo has started.
        builder.AddStartupTask((sp, token) => {
            // access instance of IMyService
            IMyService service = sp.GetRequiredService<IMyService>();

            //...use service as needed

            return Task.CompletedTask;
        });
    })
    .ConfigureServices(services => {
        services.AddSingleton<IMyService, MyService>();
    })
    .RunConsoleAsync();

Upvotes: 2

Related Questions