private static void AddNamedServiceImpl <TService, TImplementation>(IServiceCollection serviceCollection, string name, ServiceLifetime lifetime) where TImplementation : class { ServiceDescriptor descriptor = serviceCollection.LastOrDefault(x => x.ServiceType == typeof(NamedServiceFactory <TService>)); var factory = descriptor?.ImplementationInstance as NamedServiceFactory <TService>; if (factory is null) { factory = new NamedServiceFactory <TService>(); serviceCollection.AddSingleton(factory); } factory.Register <TImplementation>(name); // We don't want to register using the service descriptor since that would mean multiple TService types // would be registered causing resolution problems for non-named registrations. switch (lifetime) { case ServiceLifetime.Singleton: serviceCollection.AddSingleton <TImplementation>(); break; case ServiceLifetime.Scoped: serviceCollection.AddScoped <TImplementation>(); break; case ServiceLifetime.Transient: serviceCollection.AddTransient <TImplementation>(); break; } }
/// <summary> /// Returns an instance of the service type matching the given name. /// </summary> /// <typeparam name="TService">The type of service to return.</typeparam> /// <param name="provider">The service provider for retrieving service objects.</param> /// <param name="name">The name the service type is registered as.</param> /// <returns>The <see cref="TService"/>.</returns> public static TService GetNamedService <TService>(this IServiceProvider provider, string name) { NamedServiceFactory <TService> factory = provider.GetServices <NamedServiceFactory <TService> >().LastOrDefault(); if (factory is null) { throw new InvalidOperationException($"No service for type {typeof(TService)} named '{name}' has been registered."); } return(factory.Resolve(provider, name)); }