Arash Arash - 1 year ago 89
C# Question

Retrieving the instance of an already-registered service in Mvc Core .Net Dependency Injection

I have the following code snippet in my application:

services.AddScoped<IMyInterface, MyService>();
services.AddSingleton<IYourInterface, YourService>();

Due to some environment initialization process, I have to be able to obtain the singleton instance of IYourInterface within Startup class to call the service to read a couple of configuration entries from a remote server and populate them. How can I achieve this goal considering the fact that I am using .Net Core's built-in DI framework?

Answer Source

The way to do this to create this instance manually up front as follows:

var service = new YourService();

services.AddScoped<IMyInterface, MyService>();

Just as it is wise to separate the registration process from use (as the Microsoft.Extensions.DependencyInjection library correctly forces), this kind of separation is important between loading/building configuration and making the container registrations. Doing register-resolve-register is unsupported by libraries like MS DI, Autofac and Simple Injector, because it can lead to lots of complexity and subtle bugs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download