问题
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