dependency-injectionautofacvalidationattributetest-project

Autofac and DI for ValidationAttribute


I have the following validation attribute class:

public class ZipCodeValidationAttribute : ValidationAttribute
{
    private readonly IValidationRepository _repository;

    public override bool IsValid(object value)
    {
        var repository = _repository;

        return repository.IsPostalCodeValid((string) value);

    }
}

To test I am trying to use Autofac as my IOC and use property injection. I've set up the test as follows:

 [TestMethod]
 public void When_PostalCodeAttribute_Given_ValidPostalCode_Then_SystemReturnsTrue()
 {
        // arrange
        var value = "53051";
        var containerBuilder = new ContainerBuilder();
        containerBuilder.RegisterType<ValidationRepository>().As<IValidationRepository>().InstancePerDependency();
        containerBuilder.RegisterType<ZipCodeValidationAttribute>().PropertiesAutowired();
        var container = containerBuilder.Build();

        var attrib = container.Resolve<ZipCodeValidationAttribute>();

        // act
        var result = attrib.IsValid(value);

        // assert
        Assert.IsTrue(result);
 }

During the test my repository isn't being resolved. New to Autofac and hoping someone can point me in the right direction.


Solution

  • You need to declare the repository as a property to be auto wired by Autofac.

    public class ZipCodeValidationAttribute : ValidationAttribute
    {
        public IValidationRepository Repository { get; set; }
    
        public override bool IsValid(object value)
        {
            return Repository .IsPostalCodeValid((string) value);
        }
    }