Reputation: 8270
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?
Upvotes: 0
Views: 919
Reputation: 1846
This is an old question, but I found you can access your dependency resolution in an ActionFilterAttribute
by using the actionContext
parameter like so:
MyFooService myFooService = actionContext.Request.GetDependencyScope().GetService(typeof(MyFooService)) as MyFooService;
Upvotes: 0
Reputation: 8270
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)));
Upvotes: 0
Reputation: 2522
Attributes are metadata objects. They shouldn't be involved in database access. Use a separate service to read the attribute values and as a result access the database.
Upvotes: 1