This project is read-only.

Injecting properties in custom MVC filter attribute

May 7, 2014 at 2:06 PM
I am newbie to simple injector I try to inject my decency to my costume costume action filter on MVC 5 but it's always giving null to my dependency object "IStoreService" ,this is my sample code
    public class LogAttribute : ActionFilterAttribute 
        public String Description { get; set; }
        private IStoreService IStoreService { get; set; }

        public LogAttribute(string description )
            Description = description;


        public override void OnActionExecuting(ActionExecutingContext filterContext)
            var UserId = filterContext.HttpContext.User.Identity.Name;

I try a lot of thing without hope please anyone can provide with proper solution for this
May 7, 2014 at 2:15 PM
The IStoreService property should be public and you should have the following registration in your startup path:
Do note though that the RegisterMvcAttributeFilterProvider method will be marked obsolete in the next version of the framework and you're adviced to migrate to a different model. More information about this can be found here.
May 7, 2014 at 2:30 PM
Many Thanks for that , I will wait for 2.6 for injecting in a custom attribute , So when it will release .
Another question it's a good practice to write my log on OnActionExecuting Method ?
May 7, 2014 at 2:42 PM
We have no release date yet for v2.6. For injecting services into attributes, you don't have to wait for the next version though. You can already replace your RegisterMvcAttributeFilterProvider with the new RegisterMvcIntegratedFilterProvider, mark your properties with the [ImportAttribute] and register your custom ImportPropertySelectionBehavior as explained in the supplied link. I would say its even advisable to already move away from implicit property injection towards explicit property injection because of the clear benefits it has.

>> Another question it's a good practice to write my log on OnActionExecuting Method ?

It's hard to say anything useful about that. It really depends on what you're doing. If you're want to log some operations on the controller level, having an custom attribute might be the way to go. If you however want to log every operation, you should probably inject a filter attribute at a different stage in the MVC pipeline. The global filters would be the way to go here.

If you however want to log in a more business centric way, you might be better of going with a command/handler architecture and apply a logging decorator around your command handlers.
Marked as answer by dot_NET_Junkie on 7/15/2014 at 11:26 AM