I'm using .net core 2.2 with entityframework core. I want to write logs in database using entityframework. So I'm trying to inject DbContext to LoggerProvider.
//Main function
new WebHostBuilder().ConfigureLogging((hostingContext, logging) =>
{
logging.ClearProviders();
logging.AddDatabase(hostingContext.Configuration);
}).UseStartup<Startup>();
//Extension method
public static ILoggingBuilder AddDatabase(this ILoggingBuilder builder, IConfiguration configuration)
{
builder.AddConfiguration();
builder.Services.AddDbContext<LoggingContext>(options => options.UseSqlServer(configuration.GetConnectionString("DevelopmentConnection"), x => x.MigrationsHistoryTable("__LoggingMigrationHistory", "dbo")));
builder.Services.TryAddEnumerable(ServiceDescriptor.Scoped<ILoggerProvider, DatabaseLoggerProvider>());
builder.Services.TryAddEnumerable(ServiceDescriptor.Scoped<IConfigureOptions<LoggerOptions>, LoggerConfigurationOptions>());
builder.Services.TryAddEnumerable(ServiceDescriptor.Scoped<IOptionsChangeTokenSource<LoggerOptions>, LoggerProviderOptionsChangeTokenSource<LoggerOptions, DatabaseLoggerProvider>>());
return builder;
}
//LoggerOptions
public class LoggerOptions
{
public string LogLevel { get; set; }
}
//LoggerConfigurationOptions
public class LoggerConfigurationOptions : ConfigureFromConfigurationOptions<LoggerOptions>
{
public LoggerConfigurationOptions(ILoggerProviderConfiguration<DatabaseLoggerProvider> providerConfiguration) : base(providerConfiguration.Configuration)
{
}
}
//Logging Context
public class LoggingContext : DbContext
{
public LoggingContext(DbContextOptions<LoggingContext> options) : base(options) //In base constructor exception is thrown
{
}
}
//Logger Provider
[Microsoft.Extensions.Logging.ProviderAlias("Database")]
public class DatabaseLoggerProvider : ILoggerProvider
{
public DatabaseLoggerProvider(IOptionsMonitor<LoggerOptions> Settings, LoggingContext context) //I cannot inject context here
{
}
}
Problem is DbContext constructor throws StackOverflowException
. Can anyone tell me where I'm doing wrong?
Whoever is using LoggingContext should create a new instance, perhaps in constructor or base class constructor.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.