【问题标题】:Getting "Cannot access a disposed object" when using FV and EF in ASP.NET Core在 ASP.NET Core 中使用 FV 和 EF 时出现“无法访问已释放的对象”
【发布时间】: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&lt;Context&gt;的?如果注册正确,工厂方法应该可以实际工作
  • 我没有...我的意思是注册 Context 时无法使用 Func?我正在使用 AutoFac。但我认为注册 Context 通常 Asp.Net Core 会这样做

标签: asp.net-core fluentvalidation


【解决方案1】:

正如 cmets 中提到的,验证器默认实例化为单例,我强烈建议您不要因为性能原因而更改验证器的生命周期——它们的实例化成本非常高。

我更喜欢在 PredicateValidator(又名Must)表达式体中按需实例化轻量级 Context 对象——这种方法解决了生命周期不一致的问题。

ServiceLocator 模式示例:

public class MyValidator: AbstractValidator
{
    public MyValidator()
    {
        RuleFor(x => x.Email).Must(email => IsUnique(email)).WithMessage("email must be unique");
    }

    private IsUnique(string email)
    {
        var context = !ServiceLocator.Instance.Resolve<Context>();
        return context.Users.Any(x => x.Email == email);
    }
}

本主题可能对implementation of service locator with AutoFac 有所帮助。

【讨论】:

    猜你喜欢
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    相关资源
    最近更新 更多