0

Normally with ASP.NET Core projects, I have access to the IWebHostBuilder creation, upon which I can register services and build configuration, and then I can get into a Startup class where I can inject any of the services or configurations that were registered while building the host. I use this two-stage approach quite often, as I usually need some services available within Startup to finish registering everything else.

Now I'm working on a Generic Host headless app, adding a BackgroundService with AddHostedService<T>. There is no Startup class in this scenario, so it seems all my dependencies have to be registered while creating the HostBuilder. I'm not able to use my normal services because of the lack of the second registration step.

When using the Generic Host/non-HTTP/BackgroundService/AddHostedService approach, how can I get two stages of dependency registration as I do in Web projects?

bubbleking
  • 3,329
  • 3
  • 29
  • 49
  • builder.ConfigureServices( services => { services.AddTransient(); } ) – Dheeraj Kumar Sep 23 '20 at 02:35
  • check this out: https://stackoverflow.com/a/63603562/1204153 There is a demo project on how to do it here: https://github.com/sonicmouse/Host.CreateDefaultBuilder.Example – Andy Sep 23 '20 at 06:12
  • @Andy - Thanks. I think I replied to you on that other answer. I tried adapting what you have there to my use case, but the main thing for me is that the Startup constructor be allowed to have parameters of any type (not just IConfiguration) registered in the host builder before UseStartup was called. The reason I love the two-step registration in web projects is because I can inject services that fetch settings or process Claims (etc) and then use those services while registering the rest of the services in Startup. Here's hoping the .NET Core folks address this issue with generic host! – bubbleking Sep 23 '20 at 20:57
  • @bubbleking the `Startup` class is just a convenience class. Nothing prevents you from extracting the configuration, logging and DI calls into separate methods, or even putting them into a `Startup` class of your own. There's no need for the .NET team to add anything. – Panagiotis Kanavos Oct 05 '20 at 17:10

0 Answers0