-1

我有以下验证属性类:

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 新手,希望有人能指出我正确的方向。

4

2 回答 2

0

我在这个答案中解决了整个问题(在Validator.TryValidateetc / 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));
于 2016-02-05T09:53:02.567 回答
-1

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

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

    public override bool IsValid(object value)
    {
        return Repository .IsPostalCodeValid((string) value);
    }
}
于 2012-09-20T04:21:13.053 回答