.NET Core Dependency Injection - Force Immediate Activation

Viewed 3029

It is my understanding that injected classes aren't activated until one of the constructors are invoked (like a Controller in my MVC-project). However, is it possible to force the activation of a Singleton immediately, so I don't have to wait for a controller to be invoked? I guess I could do:

services.AddSingleton(new MySingleton());

But what if MySingleton uses DI in its constructor? Is there a way to call the constructor? Should I instead change the constructor to have the IServiceProvider as parameter and manually extract the dependencies?:

_myDependency = serviceProvider.GetService<MyDependency>();
2 Answers

Alternatively you can activate service by calling for service in configure method inside startup.cs

public void Configure(IApplicationBuilder app)
  {
       app.ApplicationServices.GetService<MySingleton>();
  } 
Related