asp.netinversion-of-controlninjectninject.web

Ninject.Web (webforms extension), injecting outside of a webform page?


I've been using the Ninject.Web extension to inject business objects, repositories, Entity Framework context etc into my application. This works very well using the [Inject] attribute which can be applied within a webform that inherits from PageBase. I am now running into a snag as I am trying to write a custom membership provider that needs injection done inside of it but of course this provider is not instantiated from within a webform. Forms Authentication will instantiate the object when it needs it. I am unsure how to about doing this without having access to the [Inject] attribute. I understand that there is an application level kernel somewhere, but I have no idea how to tap into it. Any suggestions would be greatly appreciated.


Solution

  • You do a IKernel.Inject on the the instance. Have a look at the source for the Application class in the extension project you're using.

    In the case of V2, it's in a KernelContainer. So you need to do a:

    KernelContainer.Inject( this )
    

    where this is the non-page, non application class of which you speak.

    You'll need to make sure this only happens once - be careful doing this in Global, which may get instantiated multiple times.

    Also, your Application / Global class needs to derive from NinjectHttpAppplication, but I'm sure you've that covered.