5

I'm using IHostBuilder in a .NET Core 2.1 console application. Main looks like this:

    public static async Task Main(string[] args)
    {
        var hostBuilder = new HostBuilder()
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureServices(services =>
            {
                // Register dependencies
                // ...

                // Add the hosted service containing the application flow
                services.AddHostedService<RoomService>();
            });

        await hostBuilder.RunConsoleAsync();
    }
}

Before, with IWebHostBuilder, I had the Configure() method that let me do this:

public void Configure(IApplicationBuilder applicationBuilder, IHostingEnvironment environment)
{
    // Resolve something unrelated to the primary dependency graph
    var thingy = applicationBuilder.ApplicationServices.GetRequiredService<Thingy>();
    // Register it with the ambient context
    applicationBuilder.AddAmbientThingy(options => options.AddSubscriber(thingy));

    // Use MVC or whatever
    // ...
}

This allowed me to register something ambient (using the Ambient Context pattern), not part of the application's main dependency graph. (As you can see, I still use the container to instantiate it, which is certainly preferable to newing it up manually. We could see it as a secondary, ambient dependency graph.)

With the generic host builder, we never seem to get access to the built IServiceProvider or the IApplicationBuilder. How do I achieve the same registration in this case?

Timo
  • 7,992
  • 4
  • 49
  • 67
  • Just realized it's host builder and not web. checking it out. – Nkosi Nov 26 '18 at 16:05
  • I get what you want to do. What I am having trouble understanding is where you would like to do this. – Nkosi Nov 26 '18 at 17:33
  • Reviewing [`HostBuilder` the source](https://github.com/aspnet/Hosting/blob/master/src/Microsoft.Extensions.Hosting/HostBuilder.cs), the provider is the last thing built before creating the host. Not seeing much extensibility points available to do what you have described so far. Maybe if you explain where exactly you want to this ambient configuration, we may be able to see if it is in fact possible. – Nkosi Nov 26 '18 at 17:55
  • @Nkosi I seem to have found an answer that works. I have posted it below. I think it also answers your question of where I would like to do this. – Timo Nov 27 '18 at 16:05

1 Answers1

4

Apparently, instead of calling the RunConsoleAsync() extension, we can split up the simple steps that that method takes, allowing us to do something between building and starting:

        await hostBuilder
            .UseConsoleLifetime()
            .Build()
            .AddAmbientThingy(options => options.AddSubscriber(thingy))
            .RunAsync();
Timo
  • 7,992
  • 4
  • 49
  • 67