Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if service has already been added to IServiceCollection

I am creating helper classes to simplify configuration and injection of interfaces via IServiceCollection for a library. The libraries constructor contains a number of dependencies that are likely to have been injected earlier. If they aren't already inserted into IServiceCollection, the helper class should add them. How do I detect if the interface has already been injected?

public static void AddClassLibrary(this IServiceCollection services
    , IConfiguration configuration)
{
     //Constructor for ClassLibrary requires LibraryConfig and IClass2 to be in place
     //TODO: check IServiceCollection to see if IClass2 is already in the collection. 
     //if not, add call helper class to add IClass2 to collection. 
     //How do I check to see if IClass2 is already in the collection?
     services.ConfigurePOCO<LibraryConfig>(configuration.GetSection("ConfigSection"));
     services.AddScoped<IClass1, ClassLibrary>();
}
like image 739
Dan Doney Avatar asked Mar 19 '18 23:03

Dan Doney


People also ask

How do you specify the service life for a registered service that is added as a dependency?

It automatically disposes a service instance based on the specified lifetime. Singleton − IoC container will create and share a single instance of a service throughout the application's lifetime. Transient − The IoC container will create a new instance of the specified service type every time you ask for it.

WHAT IS services in ASP.NET Core?

Dependency injection (services) ASP.NET Core includes a built-in dependency injection (DI) framework that makes configured services available throughout an app. For example, a logging component is a service. Code to configure (or register) services is added to the Startup.ConfigureServices method.

Can I inject scoped into transient?

Transient services that are stateless and don't contain any stateful dependencies can be injected into singleton or scoped services.


1 Answers

Microsoft has included extension methods to prevent services from being added if they already exist. For example:

// services.Count == 117
services.TryAddScoped<IClass1, ClassLibrary>();
// services.Count == 118
services.TryAddScoped<IClass1, ClassLibrary>();
// services.Count == 118

To use them, you need to add this using directive:

using Microsoft.Extensions.DependencyInjection.Extensions;

If the built-in methods don't meet your needs, you can check whether or not a service exists by checking for its ServiceType.

if (!services.Any(x => x.ServiceType == typeof(IClass1)))
{
    // Service doesn't exist, do something
}
like image 182
NightOwl888 Avatar answered Oct 19 '22 19:10

NightOwl888