Asp.net mvc 4 解决绑定中的单例问题<;T>;()ToMethod
Ninject 3与此代码的等价物是什么:Asp.net mvc 4 解决绑定中的单例问题<;T>;()ToMethod,asp.net-mvc-4,ninject,Asp.net Mvc 4,Ninject,Ninject 3与此代码的等价物是什么: Bind<ISession>().ToMethod(ctx => ctx.Kernel.Get<INHibernateSessionFactoryBuilder>() .GetSessionFactory() .OpenSession()) .Using<OnePerRequestBehavior>(); Bind().ToMethod(
Bind<ISession>().ToMethod(ctx => ctx.Kernel.Get<INHibernateSessionFactoryBuilder>()
.GetSessionFactory()
.OpenSession())
.Using<OnePerRequestBehavior>();
Bind().ToMethod(ctx=>ctx.Kernel.Get())
.GetSessionFactory()
.OpenSession())
.使用();
我知道我可以在RequestScope中使用
而不是使用但是如何替换ctx.Kernel.Get
?(INHibernateSessionFactoryBuilder
是一个单例)好的,只是澄清一下-由于这是在一个模块中,您仍然可以访问ctx.Kernel.Get
,但您需要使用Ninject添加代码>也作为内核提供给模块。Get
作为扩展方法公开。好的,下面是最后一段对我有效的代码:
using Infrastructure.Data;
using NHibernate;
using Ninject;
using Ninject.Modules;
using Ninject.Web.Common;
namespace Infrastructure.DependencyResolution
{
public class SessionModule : NinjectModule
{
public override void Load()
{
Bind<INHibernateSessionFactoryBuilder>().To<NHibernateSessionFactoryBuilder>().InSingletonScope();
Bind<ISession>().ToMethod(ctx => ctx.Kernel.Get<INHibernateSessionFactoryBuilder>()
.GetSessionFactory()
.OpenSession())
.InRequestScope();
}
}
}
使用基础设施。数据;
使用NHibernate;
使用Ninject;
使用Ninject.Modules;
使用Ninject.Web.Common;
命名空间基础结构.DependencyResolution
{
公共类SessionModule:ninject模块
{
公共覆盖无效负载()
{
绑定().To().InSingletonScope();
Bind().ToMethod(ctx=>ctx.Kernel.Get())
.GetSessionFactory()
.OpenSession())
.InRequestScope();
}
}
}
有了这个装有Ninject引导程序的模块,我可以使用带有NHibernate会话的存储库,而不需要在Web项目中使用NH引用…为什么要替换对ctx.Kernel.Get的调用呢?
?因为ctx.Kernel不包含Get方法…它包含,所以只需要使用Ninject添加代码>因为它是一种扩展方法。是的,我只有使用Ninject.Modules
。