Search code examples
c#dependency-injectionlight-inject

How to bind Interfaces to Methods using LightInject


In Ninject when I wanted to bind NHibernate's ISession to a method I'd do :

container.Bind<ISession>().ToMethod(CreateSession).InRequestScope();

While the method is :

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

How can I do the same with LightInject?


Solution

  • The exact equivalent is the following:

    container.Register<ISession>(factory => CreateSession(factory), new PerRequestLifeTime());
    

    where CreateSession becomes:

    private ISession CreateSession(IServiceFactory factory)
    {
        var sessionFactory = factory.GetInstance<ISessionFactory>();
        if (!CurrentSessionContext.HasBind(sessionFactory))
        {
            var session = sessionFactory.OpenSession();
            CurrentSessionContext.Bind(session);
        }
        return sessionFactory.GetCurrentSession();
    }
    

    Edit: Actualy, this is not the "exact" equivalent, because NInject's InRequestScope is related to the web request while LightInject's PerRequestLifeTime means "PerGetInstanceCall". What you would need then is to get LightInject Web extension and intialize the container this way:

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

    and use the PerScopeLifetime instead of PerRequestLifeTime