Asp.Net Core: Injecting custom data/classes into startup classes’ constructor and configure method
I’ve been working with Asp.Net core and recently came across an issue where I wanted certain information about application context which was only available at the program initialization to be available at a later time within the controller.
If read the asp.net core docs about dependency injection you will see that the custom types are registered in the ConfigureServices method of the Startup class. However, the startup class’s methods are invoked by the WebHostBuilder and it’s already past the point where the information you wanted to inject is available. By default these are the information available:
In the constructor:
IHostingEnvironment
,ILoggerFactory
In theConfigureServices
method:IServiceCollection
In theConfigure
method:IApplicationBuilder
,IHostingEnvironment
,ILoggerFactory
,IApplicationLifetime
The actual application I used this technique on was a service fabric application and I wanted information such as the application name, service name, listening address, etc which is normally only available from the activation context and service context. However, for demonstration purposes I will simply invoke the application with some arguments and return them as response in Web API.
I go through the whole process in the video below but if you don’t want to watch the short answer to the solution is to simply call ConfigureServices
manually on the WebHostBuilder
before you invoke UseStartup<Startup>()
.
It’s always obvious after you learn how it works, but I thought this might help some other people. Let me know what you think in the comments!