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>();
}
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.
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.
Transient services that are stateless and don't contain any stateful dependencies can be injected into singleton or scoped services.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With