Maxim V. Pavlov
Maxim V. Pavlov

Reputation: 10509

Resolving dependencies in Global.asax if an IoC container is initialized through WebActivator

In an ASP.NET MVC3 application, I initialize a Ninject IoC container through a

[assembly : WebActivator.PreApplicationStartMethod( typeof (NinjectMVC3), "Start" )]

A class NinjectMVC3 is responsible for my IoC container Kernel initialization.

After this is called, all controllers, that declare resolvable dependencies through a constructor variables get them resolved just fine.

But I need to use a resolved dependency in Global.asax Application_Start method, to feed it to some Custom Global Filters of mine? How can I resolve dependencies in Application_Start in my scenario?

Upvotes: 0

Views: 2267

Answers (2)

Remo Gloor
Remo Gloor

Reputation: 32725

In this case you should choose a different way. Inject the dependencies directly to your filters instead of assigning them to the global asax first. This way you solve two problems at once:

  1. The global asax does not need to know about those dependencies that it does not need itsself. You should avoid to have dependencies on objects that are just there to pass them on to other components whenever you can directly assign them to this object.
  2. You don't need to use Property injection or service location to get them into the global asax

The documentation of the Ninject.MVC3 extensions shows how you can create the filters using Ninject so that you can do constructor injection for them:

https://github.com/ninject/ninject.web.mvc/wiki/Dependency-injection-for-filters

Upvotes: 2

pjumble
pjumble

Reputation: 16960

You can use DependencyResolver.Current.GetService<T>()

Upvotes: 6

Related Questions