I am running .NET Core 2.2 app and I have a bit of code that I want to run immediately after the initial setup in Startup.cs. The class relies on a registered type and I don't really understand how I am supposed to create an instance with the dependencies already injected. Let's say I have the following class that I want to run immediately after the setup is done.
public class RunAfterStartup
{
private readonly IInjectedService _injectedService;
public RunAfterStartup(IInjectedService injectedService)
{
_injectedService = injectedService;
}
public void Foo()
{
_injectedService.Bar();
}
}
Is there a way I can run RunAfterStartup().Foo()
in Startup?
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(typeof(IInjectedService), typeof(InjectedService));
...
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
// I assume this has to go here, but could be anywhere
var runAfterStartup = MagicallyGetInstance();
runAfterStartup.Foo();
}
I know that in .NET Framework (not sure about Core) you could do this using SimpleInjector by doing something like container.GetInstance<RunAfterStartup>().Foo()
, but I'm unsure how this works in .NET Core and I'd like to just use the built-in DI.
First add RunAfterStartup
to your services in the ConfigureServices
method:
services.AddSingleton<RunAfterStartup>();
Now you can inject this class into the Configure
method:
public void Configure(IApplicationBuilder app, RunAfterStartup runAfterStartup)
{
app.UseMvc();
runAfterStartup.Foo();
}
You can access the dependency injection container from the parameters passed:
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
// I assume this has to go here, but could be anywhere
var runAfterStartup = app.ApplicationServices.GetService<IInjectedService>();
runAfterStartup.Foo();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With