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.
IInjectedService
is supposed to be injected intoRunAfterStartup
, but I suppose it doesn't matter. Probably worth pointing out that this is basically the service locator pattern which is usually an anti-pattern, particularly when the framework already supports doing proper injection for you. – Appolonia