您好我很难将HTTP范围对象传递给流畅的验证验证程序。一切正常,直到我尝试注入服务,然后它抛出以下错误
从中可以看到没有与“AutofacWebRequest”匹配的标记的范围 请求实例的范围。这通常表明 正在请求按照HTTP请求注册的组件 一个SingleInstance()组件
它归结为我认为的以下片段,我不知道如何在webapi中模仿它
public Func<T> HttpRequestScopedFactoryFor<T>(){
return () => system.Web.Mvc.DependencyResolver.Current.GetService<T>();
}
在MVC中我的autofac代码看起来像这样
public class FluentValidationModule : Module
{
public Func<T> HttpRequestScopedFactoryFor<T>()
{
return () => System.Web.Mvc.DependencyResolver.Current.GetService<T>();
}
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerRequest();
builder.RegisterInstance(HttpRequestScopedFactoryFor<ApplicationDbContext>());
}
}
}
我的FluentValidation验证码看起来像是这样
public class RoleDTOValidator : AbstractValidator<RoleDTO>
{
readonly Func<ApplicationDbContext> _dbFactory;
public RoleDTOValidator(Func<ApplicationDbContext> dbFactory)
{
_dbFactory = dbFactory;
RuleFor(m => m.Id).NotEmpty();
RuleFor(m => m.Name).NotEmpty().Must(DoesNotExist).WithMessage("Another permission exists with that name."); ;
RuleFor(m => m.Description).NotEmpty();
RuleFor(m => m.Permissions).NotEmpty().SetCollectionValidator(new ApplicationRoleClaimValidator());
}
bool DoesNotExist(RoleDTO model, string name)
{
ApplicationDbContext db = _dbFactory();
int count = db.Roles.Count(item => item.Name == name);
return count == 0;
}
}
非常感谢任何帮助。