Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register existing instances in Microsoft.Extensions.DependencyInjection?

I am migrating my .NET applications Dependency Injection framework from Unity Container to Microsoft.Extensions.DependencyInjection.

Now I did not find a way to register an already existing instance of an interface to the serviceCollection. In Unity this was possible like this:

_unityContainer.RegisterInstance<IInterface>(myObject);

In IServiceCollection I found only AddSingleton, AddScoped, AddTransient all of which only take types.

(I know doing this might be bad practice in the first place, but it is unfortunately not under my control.)

like image 806
clamp Avatar asked Oct 18 '25 21:10

clamp


1 Answers

There is an overload for AddSingleton<T> that accepts the implementation instance, e.g.:

services.AddSingleton<IInterface>(myObject);

In addition, there are overloads for AddScoped<T> and AddTransient<T> that accept a factory function as parameter. So you could register your interface like this:

services.AddScoped<IInterface>((prov) => myObject);    
services.AddTransient<IInterface>((prov) => myObject);

However, the latter misses the point of having an instance per scope or a transient instance if you always return the same instance - this is better matched with a singleton registration. This explains why there is a special overload for AddSingleton<T> in contrast to AddScoped<T> or AddTransient<T>.

like image 160
Markus Avatar answered Oct 20 '25 11:10

Markus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!