views:

18

answers:

1

I'm using StructureMap for dependency injection and I want to inject NHibernate sessions with it. I have the following code:

private static Container _container { get; set; }

static MyClass() 
{
    _container = new Container(r =>
    {
        r.For<ISessionFactory>().Singleton()
            .Use(NHibernate.GetSessionFactory());

        r.For<ISession>().HybridHttpOrThreadLocalScoped()
            .Use(_container.GetInstance<ISessionFactory>().OpenSession());
    });
}

However, I can't help but think that referencing _container from within the _container's initialization seems awkward. Is this an acceptable practice? Is it going to backfire down the road? Is there a better way? How do you handle dependencies that require the creation of another dependency to create themselves?

+1  A: 

It seems unnecessary to use a reference to an instance of the container inside the container. You have access to the container inside the Use-method through a lambda.

 r.For<ISession>().HybridHttpOrThreadLocalScoped()
  .Use(c => c.GetInstance<ISessionFactory>().OpenSession());

This will ensure that the instance is fetched every time you're in a new HttpContext. It looks to me like your way will create a singleton since the _container.GetInstance<ISessionFactory>().OpenSession() will only be executed once upon configuration.

PHeiberg
That's exactly what I was looking for. Thanks. I missed the overload that provided the container for a lambda expression.
Chris