用于ValidationAttribute的Autofac和DI

时间:2012-09-20 02:07:34

标签: dependency-injection autofac validationattribute test-project

我有以下验证属性类:

public class ZipCodeValidationAttribute : ValidationAttribute
{
    private readonly IValidationRepository _repository;

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

        return repository.IsPostalCodeValid((string) value);

    }
}

测试我试图使用Autofac作为我的IOC并使用属性注入。我按如下方式设置了测试:

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

在测试期间,我的存储库没有得到解决。 Autofac的新手,希望有人能指出我正确的方向。

2 个答案:

答案 0 :(得分:0)

我在this answer中解决了整个问题(在Validator.TryValidate etc / ASP.NET MVC等的控制下触发DI),使其能够编写:

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

使用一些辅助类(查看那里),你可以连接它,例如在ASP.NET MVC中就像在Global.asax中那样: -

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

答案 1 :(得分:-1)

您需要将repository声明为Autofac自动连接的属性。

public class ZipCodeValidationAttribute : ValidationAttribute
{
    public IValidationRepository Repository { get; set; }

    public override bool IsValid(object value)
    {
        return Repository .IsPostalCodeValid((string) value);
    }
}