Get instance of class that relies on DI in Startup class
Asked Answered
P

2

12

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.

Peachey answered 9/1, 2020 at 10:25 Comment(0)
A
8

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();
}
Appolonia answered 9/1, 2020 at 10:31 Comment(0)
F
1

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();
}
Froehlich answered 9/1, 2020 at 10:36 Comment(3)
I think IInjectedService is supposed to be injected into RunAfterStartup, 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
Wouldn't this just give me an instance of the IInjectedService? I would need that instance in the RunAfterStartup.Peachey
Oh, yeah sorry, copy/paste mistake. Just register your RunAfterStartup class and then use GetService<RunAfterStartup>Froehlich

© 2022 - 2024 — McMap. All rights reserved.