2using Microsoft.Extensions.DependencyInjection;
3using Microsoft.Extensions.Logging;
10public static class ServiceCollectionExtensions
18 public static IServiceCollection AddEngineLogging(
this IServiceCollection services)
20 ArgumentNullException.ThrowIfNull(services);
23 services.AddLogging();
28 var factoryDescriptor = services.Last(descriptor =>
29 descriptor.ServiceType == typeof(ILoggerFactory)
30 && !descriptor.IsKeyedService);
35 if (factoryDescriptor.ImplementationInstance is ILoggerFactory existingFactory)
37 EngineLogger.Initialize(existingFactory);
44 services.Remove(factoryDescriptor);
47 ServiceDescriptor.Describe(
48 typeof(ILoggerFactory),
51 var factory = CreateLoggerFactory(provider, factoryDescriptor);
52 EngineLogger.Initialize(factory);
56 factoryDescriptor.Lifetime));
61 private static ILoggerFactory CreateLoggerFactory(
62 IServiceProvider provider,
63 ServiceDescriptor descriptor)
65 if (descriptor.ImplementationFactory is not
null)
67 return (ILoggerFactory)descriptor.ImplementationFactory(provider);
70 if (descriptor.ImplementationType is not
null)
72 return (ILoggerFactory)ActivatorUtilities.CreateInstance(
74 descriptor.ImplementationType);
77 throw new InvalidOperationException(
78 "The registered ILoggerFactory service could not be constructed.");