I have an Entity Framework Core interceptor that has to get some configuration that's declared as so:
builder.Services.Configure<AppConfig>(builder.Configuration.GetSection("AppConfig"));
I'm having a hard time registering the interceptor since I can't use the AppConfig
when overriding OnConfiguring
.
I found a way to add it when configuring services here and followed this SO question. The solution can't work here because (I presume) the AppConfig
is only created after building.
var someInterceptor = new SomeInterceptor(/*this takes AppConfig as an argument*/);
builder.Services.AddSingleton(someInterceptor);
....AddInterceptors(someInterceptor);
What can I do with this? Is it possible to inject this into the interceptor?
I have an Entity Framework Core interceptor that has to get some configuration that's declared as so:
builder.Services.Configure<AppConfig>(builder.Configuration.GetSection("AppConfig"));
I'm having a hard time registering the interceptor since I can't use the AppConfig
when overriding OnConfiguring
.
I found a way to add it when configuring services here and followed this SO question. The solution can't work here because (I presume) the AppConfig
is only created after building.
var someInterceptor = new SomeInterceptor(/*this takes AppConfig as an argument*/);
builder.Services.AddSingleton(someInterceptor);
....AddInterceptors(someInterceptor);
What can I do with this? Is it possible to inject this into the interceptor?
Share Improve this question edited Mar 13 at 1:39 Zhi Lv 22k1 gold badge27 silver badges37 bronze badges asked Mar 2 at 22:43 davedave 155 bronze badges 1 |1 Answer
Reset to default 2Actually, in more modern times (.NET6+ with ConfigurationManager) you don't need to build the configuration to get values from it. You can just:
var appConfig = builder.Configuration.GetSection("AppConfig").Get<AppConfig>();
var someInterceptor = new SomeInterceptor(appConfig);
builder.Services.AddSingleton(someInterceptor);
That being said, in the blogpost you linked, there is a cleaner approach used -
services.AddDbContext<AppDbContext>((provider, options) =>
{
options.UseSqlServer(Configuration.GetConnectionString("<connection-string-name>"));
// 3. Resolve the interceptor from the service provider
options.AddInterceptors(provider.GetRequiredService<AadAuthenticationDbConnectionInterceptor>());
});
if you make IOptions<AppConfig>
(or another options-pattern type with appropriate lifetime for your use case) a dependency of the interceptor it will get resolved correctly.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745115558a4612106.html
var myConfig = JsonSerializer.Deserialize(File.ReadAllText("appconfig.sux.json"));
? – The Thirsty Ape Commented Mar 3 at 3:28