在Ninject中,当我想将NHibernate的ISession绑定到我要做的方法时:
container.Bind<ISession>().ToMethod(CreateSession).InRequestScope();
而方法是:
private ISession CreateSession(IContext context)
{
var sessionFactory = context.Kernel.Get<ISessionFactory>();
if (!CurrentSessionContext.HasBind(sessionFactory))
{
var session = sessionFactory.OpenSession();
CurrentSessionContext.Bind(session);
}
return sessionFactory.GetCurrentSession();
}
如何使用LightInject进行同样的操作?
确切的等价物如下:
container.Register<ISession>(factory => CreateSession(factory), new PerRequestLifeTime());
CreateSession变为:
private ISession CreateSession(IServiceFactory factory)
{
var sessionFactory = factory.GetInstance<ISessionFactory>();
if (!CurrentSessionContext.HasBind(sessionFactory))
{
var session = sessionFactory.OpenSession();
CurrentSessionContext.Bind(session);
}
return sessionFactory.GetCurrentSession();
}
编辑:实际上,这并不是"完全"等效的,因为NInject的InRequestScope与web请求相关,而LightInject的PerRequestLifeTime意味着"PerGetInstanceCall"。然后,您需要的是获得LightInjectWeb扩展并以这种方式初始化容器:
var container = new ServiceContainer();
container.EnablePerWebRequestScope();
container.Register<IFoo, Foo>(new PerScopeLifetime());
并使用PerScopeLifetime而不是PerRequestLifeTime