【发布时间】:2021-11-08 21:19:57
【问题描述】:
我正在尝试注册一个单例类,在 Startup.ConfigureServices 方法中提供构造函数参数。
经过几次尝试,我仍然无法使 dbContext 注入工作
public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc();
services.AddDbContext<EFContext>();
services.AddSingleton<OPCClient>(x =>
{
string endpointURL = "opc.tcp://xxx.yyy.zzz.nnn:12345";
bool autoAccept = false;
int stopTimeout = Timeout.Infinite;
var efContext = x.GetService<EFContext>();
OPCClient client = new OPCClient(endpointURL, autoAccept, stopTimeout, efContext);
client.Run();
return client;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// warmup
app.ApplicationServices.GetService<OPCClient>();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<OPCService>();
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
});
});
当var efContext = x.GetService<EFContext>(); 被执行时,我得到了异常
System.InvalidOperationException: 'Cannot resolve scoped service 'EFContext' from root provider.'
感谢您在 OPCClient 类中注入 DbContext 的任何帮助
【问题讨论】:
-
我认为您可能正在尝试将 Scoped (EFContext) 解析/注入到 Singleton (OPCClient) 生命周期中?看看这里的注释docs.microsoft.com/en-us/dotnet/core/extensions/…
标签: c# .net-core entity-framework-core