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

梦想的初衷 提交于 2019-12-11 07:33:15

问题


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.


回答1:


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.




回答2:


You don't have to use the service locator pattern, just inject into properties of your custom membership provider in Application_Start. Assuming you've registed the providers properly you can do this with something like:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        // Inject account repository into our custom membership & role providers.
        _kernel.Inject(Membership.Provider);

        // Register the Object Id binder.
        ModelBinders.Binders.Add(typeof(ObjectId), new ObjectIdModelBinder()); 
    }

I've written up a more in depth explanation here:

http://www.danharman.net/2011/06/23/asp-net-mvc-3-custom-membership-provider-with-repository-injection/




回答3:


you may need to use the Service Locator pattern, since you have no control over the creation of the membership provider.



来源:https://stackoverflow.com/questions/3907797/ninject-web-webforms-extension-injecting-outside-of-a-webform-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!