2016-07-29 91 views
2

上的ASP.NET核心应用启动我有以下几点:获得“无法访问已释放的对象”在ASP.NET中使用的核心和FV EF当

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 

我缺少什么?

+0

将'AddFluentValidation'注册为单例吗?你不能在单例中注入DbContext,因为默认设置是'DbContext'被注册为有效范围的服务并在每个请求之后得到处理(以避免DbContext跟踪状态的内存泄漏) – Tseng

+0

是的,流利的验证作为单例添加。但我也尝试注入一个Func ,我得到了同样的错误。我是不是该? –

+0

你是如何注册'Func '?如果注册正确,工厂方法应该可以正常工作 – Tseng

回答

1

正如评论中所提到的,默认情况下,验证器实例化为单例,我强烈建议您不要因为性能原因更改验证程序生命周期 - 实例化它们非常昂贵。

我更愿意在需要时实例化轻量级上下文对象PredicateValidator(又名Must)表达式体 - 这种方法解决了生命期差异问题。

例与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是有帮助的。

相关问题