具有ValidationAttribute的Autofac属性注入 [英] Autofac property injection with ValidationAttribute
问题描述
我有一个ValidationAttribute,看起来像这样:
public class RegistrationUniqueNameAttribute : ValidationAttribute
{
public IRepository<User> UserRepository { get; set; }
public override bool IsValid(object value)
{
//use UserRepository here....
}
}
在我的容器设置中(在应用启动时),我有以下内容:
builder.Register(c => new RegistrationUniqueEmailAttribute
{
UserRepository = c.Resolve<IRepository<User>>()
});
但是,在调试时,UserRepository的值始终为null,因此不会注入该属性.
我的容器设置错误吗?
我真的宁愿不必使用DependencyResolver.Current.GetService<IRepository<User>>()
,因为这不是可测试的...
不,Autofac v3对ValidationAttribute
并没有做任何特别的事情,朋友[[c2>做很多强大的事情,例如,使用过滤器属性]./p>
在此答案中,我间接解决了问题,使一个人可以编写:
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 ...)
I've got a ValidationAttribute that looks like this:
public class RegistrationUniqueNameAttribute : ValidationAttribute
{
public IRepository<User> UserRepository { get; set; }
public override bool IsValid(object value)
{
//use UserRepository here....
}
}
In my container setup (in app start) I have this:
builder.Register(c => new RegistrationUniqueEmailAttribute
{
UserRepository = c.Resolve<IRepository<User>>()
});
However, when debugging, the value of UserRepository is always null, so the property isn't getting injected.
Have I set up my container wrong?
I'd really rather not have to use DependencyResolver.Current.GetService<IRepository<User>>()
as this isn't as testable...
No, Autofac v3 doesn't do anything special with ValidationAttribute
and friends [Autofac.Mvc
does lots of powerful things e.g., with filter attributes].
I solved the problem indirectly 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);
}
}
(And some helper classes inc wiring to ASP.NET MVC...)
这篇关于具有ValidationAttribute的Autofac属性注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!