user3550283
user3550283

Reputation: 169

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?

Upvotes: 0

Views: 427

Answers (1)

uzul
uzul

Reputation: 1136

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

Upvotes: 2

Related Questions