I'm trying to setup a custom model validator provider using FluentValidation. Everything works until i try to inject a business layer manager into the validator's constructor to run some business logic.
public class Repository : IRepository
{
public Repository(IDbConnection)
{
}
}
public class Manager : IManager
{
public Manager(IRepository)
{
}
}
public AutofacValidatorFactory : ValidatorFactoryBase
{
}
public MyModelValidator : AbstractValidator<MyModel>
{
public MyModelValidator(IManager) { }
}
I wire everything up like so:
builder.Register(c => new SqlConnection(ConfigurationManager.ConnectionStrings["MyCS"].ConnectionString))
.As<IDbConnection>().InstancePerApiRequest();
builder.RegisterType<Repository>()
.As<IRepository>()
.InstancePerDependency();
builder.RegisterType<Manager>()
.As<IManager>()
.InstancePerDependency();
builder.RegisterType<ValidatorFactory>()
.As<IValidatorFactory>()
.InstancePerLifetimeScope();
builder.RegisterType<FluentValidation.Mvc.WebApi.FluentValidationModelValidatorProvider>()
.As<ModelValidatorProvider>()
.InstancePerLifetimeScope();
AssemblyScanner.FindValidatorsInAssembly(assembly)
.ForEach(
result =>
Builder.RegisterType(result.ValidatorType).As(result.InterfaceType).InstancePerApiRequest());
Finally, i add the FluentValidator Model Provider like so:
// _validatorProvider is injected as per Autofac config above.
GlobalConfiguration.Configuration.Services.Add(typeof(ModelValidatorProvider), _validatorProvider);
The issue is occurring when my validator factory tries to spin up a validator instance. At which point i get the following exception:
"No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself."
I think the issue has something to do with the way Manager & Repository is configured in Autofac but i don't know what i'm missing.
EDIT: This issue is occurring in a Web API project.