【问题标题】:How to use Ninject in an ASP.NET MVC Application for non-MVC objects如何在 ASP.NET MVC 应用程序中为非 MVC 对象使用 Ninject
【发布时间】:2012-04-12 03:06:53
【问题描述】:

我有一个使用 Ninject(NuGet 安装)的 ASP.NET MVC 3 项目。我试图了解如何使用它将依赖项注入非 MVC 对象。

我有一些类似于下面的代码。如何使用 Ninject 在下面的对象中获取 IStore 的具体实例?

public class SomeObject
{
    private static IStore _store;

    public static IStore CurrentStore
    {
        get 
        {
            if (_store == null)
            {
                // Get Instance of _store.
            }
            return _store; 
        }
    }
}

在 Global.asax 中:

protected Application_BeginRequest()
{
    IStore store = SomeObject.CurrentStore;
} 

在 NinjectWebCommon.cs 中:

    private static void RegisterServices(IKernel kernel)
    {
        // Module that binds a concrete type of IStore.
        kernel.Load<WebModule>();
    }

【问题讨论】:

    标签: ninject ninject.web.mvc


    【解决方案1】:

    对于请求处理,最简单的方法不是在 global.asax 中而是在 IHttpModule 中进行。如果为 HttpModule 添加绑定,则可以将依赖项作为构造函数参数:

    Bind<IHttpModule>().To<MyHttpModule>();
    

    【讨论】:

    • 这个方法工作正常,除了它意味着我必须检查 _store 是否为 null 并在我的模块中设置它的值,该模块将针对每个请求运行。有没有更清洁的方法?
    【解决方案2】:

    看起来这混淆了 DI 容器和 Web 应用程序之间的界限。

    您可能需要一个类来检索商店。然后这个类可以决定从哪里实际检索存储。它还包含可以在启动时调用的初始化例程。

    这样,您的 Ninject 模块不会在其中获取 Web 应用程序代码,您可以根据上下文配置商店的加载方式(例如,测试可能与生产不同)。

    【讨论】:

      猜你喜欢
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      相关资源
      最近更新 更多