我一直在使用 Ninject.Web 扩展将业务对象、存储库、实体框架上下文等注入到我的应用程序中。使用 [Inject] 属性效果非常好,该属性可以应用在继承自 PageBase 的 Web 表单中。我现在遇到了一个障碍,因为我正在尝试编写一个自定义会员资格提供程序,需要在其中完成注入,但当然该提供程序不是从网络表单中实例化的。表单身份验证将在需要时实例化该对象。我不确定如何在无法访问 [Inject] 属性的情况下执行此操作。我知道某个地方有一个应用程序级内核,但我不知道如何利用它。任何建议将不胜感激。
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.
发布评论
评论(3)
您不必使用服务定位器模式,只需在 Application_Start 中注入自定义成员资格提供程序的属性即可。假设您已经正确注册了提供商,您可以通过以下方式执行此操作:
我在这里写了更深入的解释:
http://www.danharman.net/2011/06/23/asp-net-mvc-3-自定义成员资格提供者与存储库注入/
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:
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/
您在实例上执行
IKernel.Inject
。查看您正在使用的扩展项目中的 Application 类的源代码。对于 V2,它位于
内核容器
。因此,您需要执行以下操作:其中
this
是您所说的非页面、非应用程序类。您需要确保这只发生一次 - 在
Global
中执行此操作时要小心,它可能会被实例化多次。此外,您的 Application / Global 类需要从 NinjectHttpAppplication,但我相信您已经了解了。
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: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.您可能需要使用 服务定位器 模式,因为您无法控制关于会员提供商的创建。
you may need to use the Service Locator pattern, since you have no control over the creation of the membership provider.