Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading