8
我使用FluentValidation庫執行我的車型之一的唯一約束:注入的DbContext成FluentValidation驗證
public class Foo {
// No two Foos can have the same value for Bar
public int Bar { get; set; }
}
public class FooValidator : AbstractValidator<Foo> {
public FooValidator(ApplicationDbContext context) {
this.context = context;
RuleFor(m => m.Bar)
.Must(BeUnique).WithMessage("Bar must be unique!");
}
private readonly ApplicationDbContext context;
public bool BeUnique(int bar) {
return !context.Foos.Any(foo => foo.Bar == bar);
}
}
的ApplicationDbContext
值使用StructureMap注入。爲了確保在每次請求結束時處理上下文,我試圖在我的應用程序的EndRequest
處理程序中調用ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects()
。
不幸的是,看起來,Application_EndRequest
方法被調用之前我驗證類是能夠做的工作和上下文被執行FooValidator.BeUnique
的時間佈置。
有沒有更好的方法來使用FluentValidation庫執行數據庫相關的驗證,或者是將此邏輯移到別處(控制器操作,數據庫本身或其他地方)的唯一解決方案?
也許驗證器不是http作用域(但是單例),它不會被重新創建/注入新的上下文嗎?那麼也許它會嘗試從以前的請求中使用已放置的上下文?只是猜測,我不具體地瞭解StructureMap。 –
您的評論是正確的,驗證類是Singleton作用域。想要提交這個答案,所以我可以給它信用? –