Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get instance of class that relies on DI in Startup class

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.

like image 863
Xzenon Avatar asked Jan 09 '20 10:01

Xzenon


2 Answers

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();
}
like image 83
DavidG Avatar answered Nov 06 '22 01:11

DavidG


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();
}
like image 37
nvoigt Avatar answered Nov 05 '22 23:11

nvoigt