using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Umbraco.Cms.Core.Composing; namespace Umbraco.Extensions { public static class ServiceCollectionExtensions { /// /// Adds a service of type with an implementation type of to the specified . /// /// /// Removes all previous registrations for the type . /// public static void AddUnique( this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Singleton) where TService : class where TImplementing : class, TService { services.RemoveAll(); services.Add(ServiceDescriptor.Describe(typeof(TService), typeof(TImplementing), lifetime)); } /// /// Adds services of types & with a shared implementation type of to the specified . /// /// /// Removes all previous registrations for the types & . /// public static void AddMultipleUnique( this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Singleton) where TService1 : class where TService2 : class where TImplementing : class, TService1, TService2 { services.AddUnique(lifetime); services.AddUnique(factory => (TImplementing)factory.GetRequiredService(), lifetime); } // TODO(V11): Remove this function. [Obsolete("This method is functionally equivalent to AddSingleton() please use that instead.")] public static void AddUnique(this IServiceCollection services) where TImplementing : class { services.RemoveAll(); services.AddSingleton(); } /// /// Adds a service of type with an implementation factory method to the specified . /// /// /// Removes all previous registrations for the type . /// public static void AddUnique( this IServiceCollection services, Func factory, ServiceLifetime lifetime = ServiceLifetime.Singleton) where TService : class { services.RemoveAll(); services.Add(ServiceDescriptor.Describe(typeof(TService), factory, lifetime)); } /// /// Adds a singleton service of the type specified by to the specified . /// /// /// Removes all previous registrations for the type specified by . /// public static void AddUnique(this IServiceCollection services, Type serviceType, object instance) { services.RemoveAll(serviceType); services.AddSingleton(serviceType, instance); } /// /// Adds a singleton service of type to the specified . /// /// /// Removes all previous registrations for the type type . /// public static void AddUnique(this IServiceCollection services, TService instance) where TService : class { services.RemoveAll(); services.AddSingleton(instance); } internal static IServiceCollection AddLazySupport(this IServiceCollection services) { services.Replace(ServiceDescriptor.Transient(typeof(Lazy<>), typeof(LazyResolve<>))); return services; } } }