我已经看到了许多使用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的任何想法?
答案 0 :(得分:14)
ToConstant(MvcApplication.CurrentSession)
。您想要的是延迟评估ToMethod(ctx => MvcApplication.CurrentSession)