Search code examples
c#dependency-injectionunity-containerclass-libraryactionfilterattribute

How can get access to Unity container in a class library ActionFilterAttribute?


So, I have a web project that utilizes Unity to inject UserRepository for interfaces IUserRepository. I have a class library which contains a custom ActionFilterAttribute. This custom attribute class is used on many actions already. I want to add some code to it to check for a value in the database based on a user. To do this, I need access to the UserRepository. I could do it the old fashioned way with using statements and directly access UserRepository, but I would like to utilize the DI and resolve IUserRepository. How can I get access to what the web is resolving IUserRepository to, inside the custom attribute class since ActionFilterAttribute needs an empty constructor?


Solution

  • So, although I decided to not do the user check inside the custom attribute, the solution to allow for the injection inside the custom attribute can be used elsewhere. I had a property in the attribute:

    public IUserRepository UserRepository { get; set; }
    

    In the web's Global.asax.cs, I injected it via a property injection:

    container.RegisterType<NameOfCustomAttribute>(new InjectionProperty("UserRepository", 
                                            new UserRepository(ConfigurationManager.ConnectionStrings["DBName"].ConnectionString)));