C# 如何使用LightInject将接口绑定到方法
在Ninject中,当我想将NHibernate的ISession绑定到一个方法时,我会:C# 如何使用LightInject将接口绑定到方法,c#,dependency-injection,light-inject,C#,Dependency Injection,Light Inject,在Ninject中,当我想将NHibernate的ISession绑定到一个方法时,我会: container.Bind<ISession>().ToMethod(CreateSession).InRequestScope(); container.Bind().ToMethod(CreateSession).InRequestScope(); 而方法是: private ISession CreateSession(IContext context) { var ses
container.Bind<ISession>().ToMethod(CreateSession).InRequestScope();
container.Bind().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();
}
专用ISession CreateSession(IContext上下文)
{
var sessionFactory=context.Kernel.Get();
如果(!CurrentSessionContext.HasBind(sessionFactory))
{
var session=sessionFactory.OpenSession();
CurrentSessionContext.Bind(会话);
}
返回sessionFactory.GetCurrentSession();
}
如何使用LightInject执行相同的操作?确切的等效项如下所示:
container.Register<ISession>(factory => CreateSession(factory), new PerRequestLifeTime());
container.Register(工厂=>CreateSession(工厂),新的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();
}
专用ISession CreateSession(iSeviceFactory工厂)
{
var sessionFactory=factory.GetInstance();
如果(!CurrentSessionContext.HasBind(sessionFactory))
{
var session=sessionFactory.OpenSession();
CurrentSessionContext.Bind(会话);
}
返回sessionFactory.GetCurrentSession();
}
编辑:实际上,这并不是“精确”等价物,因为NInject的InRequestScope与web请求相关,而LightInject的PerRequestLifeTime表示“PerGetInstanceCall”。
然后,您需要通过以下方式获取并初始化容器:
var container = new ServiceContainer();
container.EnablePerWebRequestScope();
container.Register<IFoo, Foo>(new PerScopeLifetime());
var container=newservicecainer();
container.EnablePerWebRequestScope();
container.Register(新PerScopeLifetime());
使用PerScopeLifetime而不是PerRequestLifeTime你在这方面取得了多大进展?LightInject中没有等价物。但是仍然有一些类型化工厂,它们很不错。为了提高性能和易用性,我刚刚开始使用LightInject(我使用的是Ninject)。阅读:避免500磅大猩猩(统一与城堡)。我将在今晚晚些时候发布我的最终结果,我们可以比较笔记。