0

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.