1

我一直在使用 Ninject.Web 扩展将业务对象、存储库、实体框架上下文等注入我的应用程序。使用可以在从 PageBase 继承的网络表单中应用的 [Inject] 属性非常有效。我现在遇到了一个障碍,因为我正在尝试编写一个需要在其中完成注入的自定义成员资格提供程序,但当然这个提供程序不是从网络表单中实例化的。Forms Authentication 将在需要时实例化对象。我不确定如何在没有访问 [Inject] 属性的情况下执行此操作。我知道某处有一个应用程序级内核,但我不知道如何利用它。任何建议将不胜感激。

4

3 回答 3

2

您不必使用服务定位器模式,只需在 Application_Start 中注入自定义成员资格提供程序的属性即可。假设您已经正确注册了提供程序,您可以使用以下方法执行此操作:

    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()); 
    }

我在这里写了更深入的解释:

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

于 2011-06-24T00:13:23.670 回答
1

IKernel.Inject在实例上做一个。查看您正在使用的扩展项目中的 Application 类的源代码。

对于 V2,它位于KernelContainer. 所以你需要做一个:

KernelContainer.Inject( this )

this您所说的非页面非应用程序类在哪里。

您需要确保这只发生一次 - 小心在 中执行此操作Global,这可能会被实例化多次。

此外,您的 Application /Global类需要从NinjectHttpAppplication派生,但我相信您已经涵盖了。

于 2010-10-11T22:47:27.667 回答
0

您可能需要使用服务定位器模式,因为您无法控制成员资格提供程序的创建。

于 2010-10-11T20:49:56.473 回答