Autofac和DI用于ValidationAttribute [英] Autofac and DI for ValidationAttribute
本文介绍了Autofac和DI用于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);
}
}
要测试,我尝试使用Autofac作为我的IOC并使用属性注入.我将测试设置如下:
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);
}
在测试期间,我的存储库未解决. Autofac的新手,希望有人可以指出正确的方向.
During the test my repository isn't being resolved. New to Autofac and hoping someone can point me in the right direction.
推荐答案
您需要将repository
声明为由Autofac自动连线的属性.
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);
}
}
这篇关于Autofac和DI用于ValidationAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文