Hello,
I have bit problem with FluentValidation using together with StructureMap and EntityFramework.
My code looks :
// Structure map config :
publicclass StructureMapConfig { publicstaticvoid StructureMapInit() { var container = Init(); DependencyResolver.SetResolver(new StructureMapDependencyResolver(container)); GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container); } privatestatic IContainer Init() { ObjectFactory.Initialize(x => { AssemblyScanner.FindValidatorsInAssembly(Assembly.GetExecutingAssembly()).ForEach(s => { x.For(s.InterfaceType).HttpContextScoped().Use(s.ValidatorType); }); // aditional configuration include dbcontext (httpcontextscoped) }); return ObjectFactory.Container; }}
// StructureMapValidatorFactory
publicclass StructureMapValidatorFactory : ValidatorFactoryBase { publicoverride IValidator CreateInstance(Type validatorType) { return ObjectFactory.TryGetInstance(validatorType) as IValidator; } }
// Globall.asax
protectedvoid Application_Start() { AreaRegistration.RegisterAllAreas(); ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(new StructureMapValidatorFactory())); FluentValidationModelValidatorProvider.Configure(); validation StructureMapConfig.StructureMapInit(); ... } protectedvoid Application_EndRequest(object sender, EventArgs e) { ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects(); }
// validator with simple view model
publicclass CreateCategoryVM { publicstring Name { get; set; } publicint ParentId { get; set; } } publicclass CreateCategoryVMValidator : AbstractValidator<CreateCategoryVM> { privatereadonly IDbContext _dbContext; // injectpublic CreateCategoryVMValidator(IDbContext dbContext) { _dbContext = dbContext; RuleFor(v => v.Name) .NotEmpty() .Must((x, e) => IsCategoryNameUnique(x.Name,x.ParentId)) } privatebool IsCategoryNameUnique(string name,int parentId) { // db callreturn !_domainContext.Set<ProcessCategory>() .Any(x => x.ParentId == parentId && x.Name == name); }
}
Well, if structure map configuration set to HttpContextScoped(), validation works fine. But create validator each request is bit expensive, right? So, i am changed structure map configuration set to Singleton. When validator is created once per application, dbContext throw dispose exception. So, is here any workaround or validator must be instanced per request if validator call to db? Thanks