M. *_*ski 39 c# dependency-injection .net-core asp.net-core asp.net-core-2.0
当我尝试Configure
在Startup.cs
文件中的方法中使用自定义DbContext时,我收到以下异常.我在版本2.0.0-preview1-005977中使用ASP.NET Core
未处理的异常:System.Exception:无法为类型为"Communicator.Backend.Startup"的方法"Configure"的参数"dbContext"解析类型为"Communicator.Backend.Data.CommunicatorContext"的服务.---> System.InvalidOperationException:无法从根提供程序解析作用域服务"Communicator.Backend.Data.CommunicatorContext".
当我尝试接收其他实例时,也会抛出此异常.
未处理的异常:System.Exception:无法解析类型为"Communicator.Backend.Services.ILdapService"的服务
...
这是我ConfigureServices
和Configure
方法.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CommunicatorContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddCookieAuthentication();
services.Configure<LdapConfig>(Configuration.GetSection("Ldap"));
services.AddScoped<ILdapService, LdapService>();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, CommunicatorContext dbContext, ILdapService ldapService)
{
app.UseAuthentication();
app.UseWebSockets();
app.Use(async (context, next) =>
{
if (context.Request.Path == "/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
await Echo(context, webSocket);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
app.UseMvc();
DbInitializer.Initialize(dbContext, ldapService);
}
Run Code Online (Sandbox Code Playgroud)
Nko*_*osi 65
引用文档
ASP.NET Core依赖注入在应用程序启动期间提供应用程序服务.您可以通过在
Startup
类的构造函数或其中一个Configure
或多个ConfigureServices
方法中包含适当的接口作为参数来请求这些服务.
Startup
按照调用它们的顺序查看类中的每个方法,可以请求以下服务作为参数:
- 在构造函数中:
IHostingEnvironment
,ILoggerFactory
- 在
ConfigureServices
方法中:IServiceCollection
- 在该
Configure
方法中:IApplicationBuilder
,IHostingEnvironment
,ILoggerFactory
,IApplicationLifetime
您正在尝试解决启动期间不可用的服务,
...CommunicatorContext dbContext, ILdapService ldapService) {
Run Code Online (Sandbox Code Playgroud)
这会给你带来的错误.如果您需要访问实现,则需要执行以下操作之一:
修改ConfigureServices
方法并从服务集合中访问它们.即
public IServiceProvider ConfigureServices(IServiceCollection services) {
services.AddDbContext<CommunicatorContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddCookieAuthentication();
services.Configure<LdapConfig>(Configuration.GetSection("Ldap"));
services.AddScoped<ILdapService, LdapService>();
services.AddMvc();
// Build the intermediate service provider
var serviceProvider = services.BuildServiceProvider();
//resolve implementations
var dbContext = serviceProvider.GetService<CommunicatorContext>();
var ldapService = serviceProvider.GetService<ILdapService>();
DbInitializer.Initialize(dbContext, ldapService);
//return the provider
return serviceProvider();
}
Run Code Online (Sandbox Code Playgroud)修改ConfigureServices
方法以返回IServiceProvider,Configure
获取a IServiceProvider
然后在那里解析依赖关系的方法.即
public IServiceProvider ConfigureServices(IServiceCollection services) {
services.AddDbContext<CommunicatorContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddCookieAuthentication();
services.Configure<LdapConfig>(Configuration.GetSection("Ldap"));
services.AddScoped<ILdapService, LdapService>();
services.AddMvc();
// Build the intermediate service provider then return it
return services.BuildServiceProvider();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory, IServiceProvider serviceProvider) {
//...Other code removed for brevity
app.UseMvc();
//resolve dependencies
var dbContext = serviceProvider.GetService<CommunicatorContext>();
var ldapService = serviceProvider.GetService<ILdapService>();
DbInitializer.Initialize(dbContext, ldapService);
}
Run Code Online (Sandbox Code Playgroud)Krz*_*cki 30
来自NKosi的解决方案是有效的,因为通过调用services.BuildServiceProvider()
自己没有参数,你没有通过validateScopes
.因为禁用此验证,所以不会抛出异常.然而,这并不意味着问题不存在.
EF Core DbContext
注册了scoped生活方式.在ASP本机DI容器范围连接到实例IServiceProvider
.通常,当您使用DbContext
from Controller时没有问题,因为ASP IServiceProvider
为每个请求创建新范围(新实例),然后使用它来解析此请求中的所有内容.但是,在应用程序启动期间,您没有请求范围.您的实例IServiceProvider
不是作用域的(换句话说,在根作用域中).这意味着您应该自己创建范围.你可以这样做:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<CommunicatorContext>();
var ldapService = scope.ServiceProvider.GetRequiredService<ILdapService>();
// rest of your code
}
// rest of Configure setup
}
Run Code Online (Sandbox Code Playgroud)
该ConfigureServices
方法可以保持不变.
编辑
您的解决方案将在2.0.0 RTM中运行,无需任何更改,因为将在RTM作用域服务提供程序中为Configure方法https://github.com/aspnet/Hosting/pull/1106创建.
Nat*_*ini 25
在ASP.NET Core 2.0及更新版本中,您可以简单地将所需的作用域服务注入Configure
构造函数中,就像您最初尝试的那样:
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
CommunicatorContext dbContext,
ILdapService ldapService)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
Bri*_*riM 17
.UseDefaultServiceProvider(options =>
options.ValidateScopes = false)
Run Code Online (Sandbox Code Playgroud)
之后在Program.cs中添加它 .UseStartup<Startup>()
适合我
另外,您可以在您的Configure
方法中创建服务范围:
var scopeFactory = ApplicationServices.GetService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
var dbContext = scope.ServiceProvider.GetService<CommunicatorDbContext>();
DbInitializer.Initializer(dbContext, ldapService);
}
Run Code Online (Sandbox Code Playgroud)
尽管如Slack所述,但不要这样做;-)
归档时间: |
|
查看次数: |
30177 次 |
最近记录: |