3

我已经看到了很多使用 ASP.NET MVC 配置 Ninject 的不同方法,但实现似乎随着 MVC 框架的每个版本而略有变化。我正在尝试将 RavenDB 会话注入我的存储库。这是我几乎可以工作的东西。

public class MvcApplication : NinjectHttpApplication
{
    ...

    protected override void OnApplicationStarted()
    {
        base.OnApplicationStarted();

        AreaRegistration.RegisterAllAreas();

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

    protected override IKernel CreateKernel()
    {
        return new StandardKernel(new MyNinjectModule());
    }

    public static IDocumentSession CurrentSession
    {
        get { return (IDocumentSession)HttpContext.Current.Items[RavenSessionKey]; }
    }
    ...
}

public class MyNinjectModule : NinjectModule
{
    public override void Load()
    {
        Bind<IUserRepository>().To<UserRepository>();
        Bind<IDocumentSession>().ToConstant(MvcApplication.CurrentSession);
    }
}

当它尝试解析 IDocumentSession 时,我收到以下错误。

Error activating IDocumentSession using binding from IDocumentSession to constant value
Provider returned null.
Activation path:
  3) Injection of dependency IDocumentSession into parameter documentSession of constructor of type UserRepository

关于如何使 IDocumentSession 解决的任何想法?

4

1 回答 1

14

ToConstant(MvcApplication.CurrentSession)在应用程序开始时进行评估。你想要的是延迟评估ToMethod(ctx => MvcApplication.CurrentSession)

于 2011-01-06T15:39:46.897 回答