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);
46 services.Add(ServiceDescriptor.Describe(
47 typeof(ILoggerFactory),
50 var factory = CreateLoggerFactory(provider, factoryDescriptor);
51 EngineLogger.Initialize(factory);
55 factoryDescriptor.Lifetime));
60 private static ILoggerFactory CreateLoggerFactory(
61 IServiceProvider provider,
62 ServiceDescriptor descriptor)
64 if (descriptor.ImplementationFactory is not
null)
66 return (ILoggerFactory)descriptor.ImplementationFactory(provider);
69 if (descriptor.ImplementationType is not
null)
71 return (ILoggerFactory)ActivatorUtilities.CreateInstance(
73 descriptor.ImplementationType);
76 throw new InvalidOperationException(
77 "The registered ILoggerFactory service could not be constructed.");