ActionFilterAttribute ninject injection - DbContext has been disposed
Q

1

8

I have my project which uses the usual Repository pattern with Services and Unit of Work (all with Ninject injecting the dependencies from a NinjectModule), but I'm trying to access a service from an ActionFilterAttribute to inject some information (from DB) in the layout of the pages I show so I don't need to mess with all the actions on each controller.

The problem comes when I save to DB on one screen and move to the next and then come back to the previous (with a standard @Url.Action): The ActionFilterAttribute for the Index action is triggered but the call to the service and corresponding repository (within the attribute) throw an exception because the DbContext has been disposed.

Is there any problem with accessing a service and, consequently, the DbContext from an ActionFilterAttribute while injecting the service via Property Injection? I want to make a note that I use property injection for the service in the attribute because the constructor receives 2 parameters that are arbitrary depending on the signature of the Action methods, so my only option was to inject via property.

Let me know if you need some code and I'll update the question.

Quadruped answered 11/1, 2013 at 19:5 Comment(1)
DB context and all the places its injected need to be bound inrequestscope (or a shorter scope)Kanishakanji
Q
3

I found the solution to my problem in the following question: Injecting dependencies into ASP.NET MVC 3 action filters. What's wrong with this approach?

Combining Mark Seeman's answer with striplingwarrior's comment was the solution to it.

Basically I splitted my ActionFilterAttribute into an Attribute that merely decorated my Actions and keeps the parameters I need for later, and also into an ActionFilter that checked the Action's custom attributes and if my attribute exists, then it injects the data I wanted from the DB into the ViewBag. Everything is later binded with the BindFilter extension from Ninject so it applies only to the methods it needs.

Quadruped answered 13/1, 2013 at 5:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.