Autofac property injection with ValidationAttribute

主宰稳场 提交于 2019-12-13 14:02:43

问题


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...


回答1:


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...)



来源:https://stackoverflow.com/questions/15879967/autofac-property-injection-with-validationattribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!