Skip to content

Instantly share code, notes, and snippets.

@jasonmitchell
Last active March 14, 2023 05:24
Show Gist options
  • Save jasonmitchell/bf3890f234c0a19db551 to your computer and use it in GitHub Desktop.
Save jasonmitchell/bf3890f234c0a19db551 to your computer and use it in GitHub Desktop.
Integrating Fluent Validation with Web API using Autofac. Full example: https://github.com/jasonmitchell/fluentvalidation-webapi-autofac
using System;
using Autofac;
using FluentValidation;
namespace Sample.Web.Infrastructure
{
public class AutofacValidatorFactory : ValidatorFactoryBase
{
private readonly IComponentContext _context;
public AutofacValidatorFactory(IComponentContext context)
{
_context = context;
}
public override IValidator CreateInstance(Type validatorType)
{
object instance;
if (_context.TryResolve(validatorType, out instance))
{
var validator = instance as IValidator;
return validator;
}
return null;
}
}
}
using System.Web.Http;
using Sample.Web.Models;
namespace Sample.Web.Controllers
{
public class PeopleController : ApiController
{
public IHttpActionResult CreatePerson(Person person)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return Ok();
}
}
}
namespace Sample.Web.Models
{
public class Person
{
public string FirstName { get; set; }
public string OtherNames { get; set; }
public string LastName { get; set; }
}
}
using FluentValidation;
namespace Sample.Web.Models
{
public class PersonValidator : AbstractValidator<Person>
{
public PersonValidator()
{
RuleFor(x => x.FirstName).NotEmpty();
RuleFor(x => x.LastName).NotEmpty();
}
}
}
using System.Web.Http.Validation;
using Autofac;
using Autofac.Integration.WebApi;
using FluentValidation;
using FluentValidation.WebApi;
namespace Sample.Web.Infrastructure
{
public class ValidationModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(ThisAssembly)
.Where(t => t.Name.EndsWith("Validator"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
builder.RegisterType<FluentValidationModelValidatorProvider>().As<ModelValidatorProvider>();
builder.RegisterType<AutofacValidatorFactory>().As<IValidatorFactory>().SingleInstance();
base.Load(builder);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment