1

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?

user2184057
  • 924
  • 10
  • 27

1 Answers1

1

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.

BatteryBackupUnit
  • 12,934
  • 1
  • 42
  • 68
  • What do u mean by IResolutionRoot? – user2184057 Aug 26 '14 at 18:28
  • 1
    the `NinjectKernel` or `StandardKernel` implements two interfaces: `IResolutionRoot` (used for instanciating objects/object graphs, p.Ex. `Get()`) and `IBindingRoot` (used for creating bindings, p.Ex `Bind()`). In your web-app the `DependencyResolver` is doing `IResolutionRoot.Get()` everytime something is instantiated. You can also have `IResolutionRoot` injected somewhere and use it to instantiate stuff. This is called `ServiceLocator` and is mostly an anti-pattern, that means, use it only if there's no better solution. – BatteryBackupUnit Aug 27 '14 at 04:59