Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac property injection with MVC ValidationAttribute

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));
}
like image 921
ThunderDev Avatar asked Sep 29 '22 19:09

ThunderDev


1 Answers

I solved my problem using the DependencyResolver class in ASP.NET MVC.

IMerchantRepo repo = DependencyResolver.Current.GetService<IMerchantRepo>();
like image 190
ThunderDev Avatar answered Oct 20 '22 15:10

ThunderDev