【发布时间】:2016-08-04 08:36:48
【问题描述】:
我在 ASP.NET Core 应用程序启动时有以下内容:
services.AddDbContext<Context>(x => x.UseSqlServer(connectionString));
services.AddFluentValidation(x => x.RegisterValidatorsFromAssemblyContaining<Startup>());
当我在 FluentValidation 验证器上注入实体框架上下文时:
public class TestModelValidator : AbstractValidator<TestModel> {
public TestModelValidator(Context context) {
}
}
我收到以下错误:
ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur is you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: Context
我错过了什么?
【问题讨论】:
-
AddFluentValidation是否注册为单例?您不能在单例中注入 DbContext,因为默认设置是DbContext注册为范围服务并在每次请求后被释放(以避免 DbContext 跟踪状态导致内存泄漏) -
是的,流利的验证添加为单例。但我也尝试注入 Func
并得到同样的错误。我应该吗? -
您是如何注册
Func<Context>的?如果注册正确,工厂方法应该可以实际工作 -
我没有...我的意思是注册 Context 时无法使用 Func?我正在使用 AutoFac。但我认为注册 Context 通常 Asp.Net Core 会这样做
标签: asp.net-core fluentvalidation