【问题标题】:Ninject with ASP.Net webforms and MVCNinject 与 ASP.Net 网络表单和 MVC
【发布时间】:2010-06-29 13:53:09
【问题描述】:

我想在一个结合了 ASP.Net webforms 和 ASP.Net MVC 的项目中使用 Ninject。我正在使用 Ninject 2,但是当我使用 Ninject.Web.Mvc 中的 NinjectHttpApplication 时,当我使用诸如未创建内核的 PageBase 之类的东西时,它会抱怨。

我在 Global.asax 中有以下内容,但不确定要添加什么。

public class MvcApplication : Ninject.Web.Mvc.NinjectHttpApplication
{
    protected override void OnApplicationStarted()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);
        RegisterAllControllersIn(Assembly.GetExecutingAssembly());
    }

    protected override Ninject.IKernel CreateKernel()
    {
        return new StandardKernel(new ServiceModule());
    }
}

有人在某个地方有这个工作,可以分享一些想法或代码吗?

【问题讨论】:

    标签: asp.net asp.net-mvc webforms ninject


    【解决方案1】:

    正如 Ruben 所说,我已经在 Ninject 邮件列表中发布了一条消息:

    http://groups.google.com/group/ninject/browse_thread/thread/317fc48387399aa6

    简而言之,很遗憾,这实际上是不可能的。但是,使用自定义 PageBase 类,您可以使属性和方法注入成为可能(来自 Nate Kohari 在 Ninject 邮件列表中的回答):

    public abstract class PageBase : Page
    {
      public IKernel Kernel { get; private set; }
      public PageBase() { Kernel = ...; }
      public void Page_Init() { Kernel.Inject(this); }
    } 
    

    【讨论】:

      【解决方案2】:

      1) 查看 Mvc 和非 Mvc Ninject Extensions 的源代码 - 代码非常简短且整洁

      2) 转到 ninject 邮件列表并提出这个问题,以及您从源代码中学到的东西。很快就会有答案或补丁闪电

      【讨论】:

      • 感谢您的回复。我已经做了 1,并尝试将两个 HttpApplications 合并为一个。但这并不“感觉正确”。我已经在 Ninject 邮件列表中添加了一条消息,当我收到有用的回复时会通知您。
      【解决方案3】:

      这里有一些关于如何在我之前收藏的网络表单中利用 DI 的非常好的资源:

      http://aspnetresources.com/articles/ioc_and_di_with_web_forms http://aspnetresources.com/articles/real_world_ioc_and_di_with_webforms

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-25
        • 2011-06-24
        • 2011-02-18
        • 1970-01-01
        • 2011-05-28
        • 1970-01-01
        相关资源
        最近更新 更多