Home > Blockchain >  How to register existing instances in Microsoft.Extensions.DependencyInjection?
How to register existing instances in Microsoft.Extensions.DependencyInjection?

Time:10-05

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

CodePudding user response:

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

  • Related