我有一个看起来像这样的ValidationAttribute:
public class RegistrationUniqueNameAttribute : ValidationAttribute
{
public IRepository<User> UserRepository { get; set; }
public override bool IsValid(object value)
{
//use UserRepository here....
}
}在我的容器设置中(在app start中)我有这样的设置:
builder.Register(c => new RegistrationUniqueEmailAttribute
{
UserRepository = c.Resolve<IRepository<User>>()
});但是,在调试时,UserRepository的值始终为空,因此不会注入该属性。
我的容器设置错误了吗?
我真的不想使用DependencyResolver.Current.GetService<IRepository<User>>(),因为它不是很容易测试……
发布于 2016-02-05 02:46:59
不,Autofac v3不会对ValidationAttribute和朋友做任何特别的事情,Autofac.Mvc会做很多强大的事情,例如,使用过滤器属性。
我间接地用in this answer解决了这个问题,使人们能够写道:
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...)
https://stackoverflow.com/questions/15879967
复制相似问题