As far as i know ASP MVC caches filters -> so they are not bound in request scope thus if i will ask ninject inside it for an instance of object i will get it in completly new scope.
In Web-Api I can use actionContext.Request.GetDependencyScope() where actionContext :: HttpActionContext to retrieve objects instances from request scope. I have been googling for some time and I cannot find anything similar in MVC. So the main qustion is :: Is there any way to retrieve object instances bound in request scope inside MVC filters?
I've had a look at the implementation of Ninject.web.mvcX InRequestScope()
.
It uses HttpContext.Current
as scope object.
That means, if you've got
Bind<IFoo>().To<Foo>().InRequestScope();
you can inject use
IResolutionRoot.Get<IFoo>()
basically anywhere/anytime at which HttpContext.Current
is "valid".
To bind the filter, you can use the ninject.web.mvcX nuget package and do:
BindFilter<FooFilter>(FilterScope.Controller, 0)
This allows you to use ctor-injection with the filter. Also see Ninject Wiki: Dependency Injection for Filters
I'm not quite sure whether this changes when / how often filters are instanciated, but i don't think so. So in order to access an InRequestScope()
object in your filter, you'll have to inject an IResolutionRoot
or - even better - a factory (see ninject.extensions.factory) into your filter to create the object / object graph.