I have found several questions on this subject, but have not found a clean and simple solution.
This is what I'm doing (using Autofac 3.3.0) for registering
builder.RegisterType<MerchantRepo>().As<IMerchantRepo>().PropertiesAutowired();
This is my validation class
public class MerchantMustBeUniqueAttribute : ValidationAttribute
{
    public IMerchantRepo MerchantRepo { get; set; }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        int merchantId = Convert.ToInt32(value);
        if (MerchantRepo.Exists(merchantId))
        {
            return new ValidationResult(ErrorMessage);
        }
        else
        {
            return ValidationResult.Success;
        }
    }
}
My merchant repo is always null.
Edit:
This is part of my view model
public class MerchantCreationModel
{
    [Required]
    [MerchantMustBeUnique(ErrorMessage = "Already exists!")]
    public int? NewMerchantId { get; set; }
}
Autofac registration
public static void RegisterDependencies()
{
    var builder = new ContainerBuilder();
    builder.RegisterFilterProvider(); // Inject properties into filter attributes
    builder.RegisterControllers(typeof(MvcApplication).Assembly);
    builder.RegisterType<MerchantRepo>().As<IMerchantRepo>().PropertiesAutowired();
    IContainer container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
                I solved my problem using the DependencyResolver class in ASP.NET MVC.
IMerchantRepo repo = DependencyResolver.Current.GetService<IMerchantRepo>();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With