Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core Dependency Injection - Force Immediate Activation

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>();
like image 701
Jeppe Avatar asked Mar 08 '23 17:03

Jeppe


2 Answers

Lets say we have a class implemented like this.

public class MySingleton {
    private readonly IMyDependency dependency;
    MySingleton(IMyDependency dependency) {
        this.dependency = dependency;
    }
}

If I understand your question correctly you are looking for something like this.

services.AddSingleton<IMyDependency, MyDependency>();
services.AddSingleton<MySingleton>(provider => new MySingleton(provider.GetService<IMyDependency>()));

This creates an implementation factory to be used to initialize your singleton when needed. It is an overload that provides the service provider when manually initializing the type.

For example if you needed access to your singleton right after registering it.

var serviceProvider = services.BuildServiceProvider();

MySingleton singleton = serviceProvider.GetService<MySingleton>();
like image 73
Nkosi Avatar answered Mar 25 '23 04:03

Nkosi


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

public void Configure(IApplicationBuilder app)
  {
       app.ApplicationServices.GetService<MySingleton>();
  } 
like image 33
kplshrm7 Avatar answered Mar 25 '23 03:03

kplshrm7