ActionFilterAttribute ninject injection - DbContext has been removed

I have my project that uses the usual repository template with Services and Unit of Work (all with Ninject introducing dependencies from NinjectModule), but I'm trying to access the service from ActionFilterAttribute in order to enter some information (from the database) in the page layout, which I show, so I don’t need to bother with all the actions on each controller.

The problem arises when I save the DB on one screen and go to the next, and then go back to the previous one (with the @Url.Action standard): ActionFilterAttribute fires for the Index action, but a call to the service and the corresponding repository (inside the attribute) throws an exception, therefore that DbContext has been disposed .

Is there a problem with accessing the service and, therefore, the DbContext from the ActionFilterAttribute when entering the service through the Injection function? I want to note that I use property injection for the service in the attribute, because the constructor receives 2 parameters, which are arbitrary depending on the signature of the Action methods, so my only option is to enter through the property.

Let me know if you need a code and I will update the question.

+8
dependency-injection entity-framework-5 asp.net-mvc-4 ninject actionfilterattribute
source share
1 answer

I found a solution to my problem in the following question: Including dependencies in ASP.NET MVC 3 action filters. What is wrong with this approach?

Mark Seeman's answer with a comment on striplingwarrior was a solution for him.

Basically, I divided my ActionFilterAttribute into an attribute that simply adorned my actions and saved the parameters that I need for later versions, as well as into an ActionFilter that checked custom Action attributes and, if my attribute exists, then it enters the database data I need in the ViewBag. Everything is later tied to the BindFilter extension from Ninject, so it applies only to the methods that it needs.

+3
source share

All Articles