如何使用LightInject将接口绑定到方法

时间:2015-03-03 15:02:34

标签: c# dependency-injection light-inject

在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做同样的事情?

1 个答案:

答案 0 :(得分:2)

确切的等价物如下:

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();
}

编辑:Actualy,这不是“精确”等价物,因为NInject的InRequestScope与Web请求相关,而LightInject的PerRequestLifeTime则表示“PerGetInstanceCall”。 你需要的是获得LightInject Web extension并以这种方式初始化容器:

var container = new ServiceContainer();
container.EnablePerWebRequestScope();                   
container.Register<IFoo, Foo>(new PerScopeLifetime());  

并使用PerScopeLifetime而不是PerRequestLifeTime