3

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

Alex
  • 37,502
  • 51
  • 204
  • 332
  • 1
    ValidationAttributes are not created by Autofac. The CLR itself is responsible for creating them. – Steven Apr 08 '13 at 13:46
  • This question implies it should work? http://stackoverflow.com/questions/12505245/autofac-and-di-for-validationattribute – Alex Apr 08 '13 at 14:44
  • This will only work when you override the default `DataAnnotationsModelValidator`, but I can't find anything about this in the Autofac source or online. Perhaps I'm missing something. – Steven Apr 08 '13 at 15:55
  • @Steven No, you're not missing anything. I've festooned the offending question with comments after enduring a similar wild goose chase. – Ruben Bartelink Feb 04 '16 at 18:24

1 Answers1

0

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

Community
  • 1
  • 1
Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249