已创建超过二十个 'IServiceProvider' 个实例供 Entity Framework 内部使用
More than twenty 'IServiceProvider' instances have been created for internal use by Entity Framework
我在 ASP.NET Core 2.2 应用程序中收到此警告
warn: Microsoft.EntityFrameworkCore.Infrastructure[10402]
More than twenty 'IServiceProvider' instances have been created for internal use by Entity Framework. This is commonly caused by
injection of a new singleton service instance into every DbContext
instance. For example, calling UseLoggerFactory passing in a new
instance each time--see https://go.microsoft.com/fwlink/?linkid=869049
for more details. Consider reviewing calls on
'DbContextOptionsBuilder' that may require new service providers to be
built.
花了一些时间后,我发现它发生在 startup.cs。我正在使用 IdentityServer3 + OpenIDCNnection 进行身份验证。
用户成功登录后,客户端应用程序授权用户确保用户存在于客户端应用程序的数据库中。
Startup.cs 客户端应用
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IAccountService, AccountService>();
services.AddDbContext<Data.Entities.MyDBContext>(options =>
{
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"),
sqlServerOptions => sqlServerOptions.CommandTimeout(sqlCommandTimeout));
});
services.AddAuthentication(options =>
{
// removed for brevity purpose
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
// removed for brevity purpose
})
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Events = new OpenIdConnectEvents()
{
OnTokenValidated = async context =>
{
Data.Entities.UserAccount userAccount = null;
using (var serviceProvider = services.BuildServiceProvider())
{
using (var serviceScope = serviceProvider.CreateScope())
{
using (var accountService = serviceScope.ServiceProvider.GetService<IAccountService>())
{
userAccount = await accountService.Authorize(userName);
}
}
}
if (userAccount == null)
{
throw new UnauthorizedAccessException(string.Format("Could not find user for login '{0}' ", userName));
}
},
};
}
);
}
}
账户服务
public class AccountService : IAccountService
{
private bool _disposed = false;
private readonly MyDBContext_dbContext;
public AccountService(MyDBContext dbContext)
{
_dbContext = dbContext;
}
public UserAccount Authorize(string userName)
{
// Ensures user exists in the database
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
if (_dbContext != null)
{
_dbContext.Dispose();
}
// Free any other managed objects here.
}
// Free any unmanaged objects here.
_disposed = true;
}
}
AccountService.Authorize(userName)
将在每次成功登录时调用。等第 21 个成功用户及以后我开始看到警告。
问题
1>在 OnTokenValidated
事件中,我正在创建服务提供者并立即处置它。为什么 EF 仍在记录警告?
2>如何摆脱这个警告?
即使我使用范围创建了 20 多个 DBContext,我也会收到此警告
(1) 您可以定义 AddDbContext 方法的 ServiceLifetime 参数,而不是处理 dbcontext。
contextLifetime: ServiceLifetime
The lifetime with which to register the DbContext service in the container.
optionsLifetime : ServiceLifetime
The lifetime with which to register the DbContextOptions service in the container.
EntityFrameworkServiceCollectionExtensions.AddDbContext Method
(2) 下面是记录器和错误陷阱的示例,可以在启动时应用于 configureservices 方法 class。
// define single service provider
using (var sp = new ServiceCollection()
.AddLogging(l => l.AddConsole())
.AddDbContext<MyDBContext>(options =>
{
options.UseSqlServer("Server=(local);Database=MyDB;Integrated Security=True",
sqlServerOptions => sqlServerOptions.CommandTimeout(120));
})
.BuildServiceProvider())
// define service logger
using (var logger = sp.GetService<ILoggerFactory>().CreateLogger<Program>())
{
try
{
for (int i = 1; i <= 25; i++)
{
using (var serviceScope = sp.CreateScope())
using (var accountService = sp.GetService<MyDBContext>())
{
}
}
}
// (2) catch the error warning
catch(ex: Exception)
{
logger.LogInformation($@"Error: {ex.ToString()}");
}
}
顺便说一句,对于声明和运行时,EF 实体肯定是静态的 classes。因此,您必须在数据库架构更改时修改(或执行任何迁移步骤)class(s)。
希望对您有所帮助。
解决了不必要的建筑服务提供商的问题。
context
参数有 HttpContext。和 HttpContext 提供对 ServiceProvider
的访问
OnTokenValidated = async context =>
{
Data.Entities.UserAccount userAccount = null;
using (var accountService = context.HttpContext.RequestServices.GetService<IAccountService>())
{
userAccount = await accountService.Authorize(userName);
}
if (userAccount == null)
{
throw new UnauthorizedAccessException(string.Format("Could not find user for login '{0}' ", userName));
}
},
我在 ASP.NET Core 2.2 应用程序中收到此警告
warn: Microsoft.EntityFrameworkCore.Infrastructure[10402] More than twenty 'IServiceProvider' instances have been created for internal use by Entity Framework. This is commonly caused by injection of a new singleton service instance into every DbContext instance. For example, calling UseLoggerFactory passing in a new instance each time--see https://go.microsoft.com/fwlink/?linkid=869049 for more details. Consider reviewing calls on 'DbContextOptionsBuilder' that may require new service providers to be built.
花了一些时间后,我发现它发生在 startup.cs。我正在使用 IdentityServer3 + OpenIDCNnection 进行身份验证。
用户成功登录后,客户端应用程序授权用户确保用户存在于客户端应用程序的数据库中。
Startup.cs 客户端应用
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IAccountService, AccountService>();
services.AddDbContext<Data.Entities.MyDBContext>(options =>
{
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"),
sqlServerOptions => sqlServerOptions.CommandTimeout(sqlCommandTimeout));
});
services.AddAuthentication(options =>
{
// removed for brevity purpose
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
// removed for brevity purpose
})
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Events = new OpenIdConnectEvents()
{
OnTokenValidated = async context =>
{
Data.Entities.UserAccount userAccount = null;
using (var serviceProvider = services.BuildServiceProvider())
{
using (var serviceScope = serviceProvider.CreateScope())
{
using (var accountService = serviceScope.ServiceProvider.GetService<IAccountService>())
{
userAccount = await accountService.Authorize(userName);
}
}
}
if (userAccount == null)
{
throw new UnauthorizedAccessException(string.Format("Could not find user for login '{0}' ", userName));
}
},
};
}
);
}
}
账户服务
public class AccountService : IAccountService
{
private bool _disposed = false;
private readonly MyDBContext_dbContext;
public AccountService(MyDBContext dbContext)
{
_dbContext = dbContext;
}
public UserAccount Authorize(string userName)
{
// Ensures user exists in the database
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
if (_dbContext != null)
{
_dbContext.Dispose();
}
// Free any other managed objects here.
}
// Free any unmanaged objects here.
_disposed = true;
}
}
AccountService.Authorize(userName)
将在每次成功登录时调用。等第 21 个成功用户及以后我开始看到警告。
问题
1>在 OnTokenValidated
事件中,我正在创建服务提供者并立即处置它。为什么 EF 仍在记录警告?
2>如何摆脱这个警告?
即使我使用范围创建了 20 多个 DBContext,我也会收到此警告
(1) 您可以定义 AddDbContext 方法的 ServiceLifetime 参数,而不是处理 dbcontext。
contextLifetime: ServiceLifetime
The lifetime with which to register the DbContext service in the container.
optionsLifetime : ServiceLifetime
The lifetime with which to register the DbContextOptions service in the container.
EntityFrameworkServiceCollectionExtensions.AddDbContext Method
(2) 下面是记录器和错误陷阱的示例,可以在启动时应用于 configureservices 方法 class。
// define single service provider
using (var sp = new ServiceCollection()
.AddLogging(l => l.AddConsole())
.AddDbContext<MyDBContext>(options =>
{
options.UseSqlServer("Server=(local);Database=MyDB;Integrated Security=True",
sqlServerOptions => sqlServerOptions.CommandTimeout(120));
})
.BuildServiceProvider())
// define service logger
using (var logger = sp.GetService<ILoggerFactory>().CreateLogger<Program>())
{
try
{
for (int i = 1; i <= 25; i++)
{
using (var serviceScope = sp.CreateScope())
using (var accountService = sp.GetService<MyDBContext>())
{
}
}
}
// (2) catch the error warning
catch(ex: Exception)
{
logger.LogInformation($@"Error: {ex.ToString()}");
}
}
顺便说一句,对于声明和运行时,EF 实体肯定是静态的 classes。因此,您必须在数据库架构更改时修改(或执行任何迁移步骤)class(s)。
希望对您有所帮助。
解决了不必要的建筑服务提供商的问题。
context
参数有 HttpContext。和 HttpContext 提供对 ServiceProvider
OnTokenValidated = async context =>
{
Data.Entities.UserAccount userAccount = null;
using (var accountService = context.HttpContext.RequestServices.GetService<IAccountService>())
{
userAccount = await accountService.Authorize(userName);
}
if (userAccount == null)
{
throw new UnauthorizedAccessException(string.Format("Could not find user for login '{0}' ", userName));
}
},