Autofac and DI for ValidationAttribute

假如想象 提交于 2019-12-13 22:01:07

问题


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.


回答1:


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);
    }
}



回答2:


I solved the whole problem (triggering DI under the control of Validator.TryValidate etc / ASP.NET MVC etc) in this answer, enabling one to write:

class MyModel 
{
    ...
    [Required, StringLength(42)]
    [ValidatorService(typeof(MyDiDependentValidator), ErrorMessage = "It's simply unacceptable")]
    public string MyProperty { get; set; }
    ....
}

public class MyDiDependentValidator : Validator<MyModel>
{
    readonly IUnitOfWork _iLoveWrappingStuff;

    public MyDiDependentValidator(IUnitOfWork iLoveWrappingStuff)
    {
        _iLoveWrappingStuff = iLoveWrappingStuff;
    }

    protected override bool IsValid(MyModel instance, object value)
    {
        var attempted = (string)value;
        return _iLoveWrappingStuff.SaysCanHazCheez(instance, attempted);
    }
}

With some helper classes (look over there), you wire it up e.g. in ASP.NET MVC like so in the Global.asax :-

DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(
    typeof(ValidatorServiceAttribute),
    (metadata, context, attribute) =>
        new DataAnnotationsModelValidatorEx(metadata, context, attribute, true));


来源:https://stackoverflow.com/questions/12505245/autofac-and-di-for-validationattribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!