开发者

StructureMap nested dependency handling

开发者 https://www.devze.com 2023-01-16 13:43 出处:网络
I\'m using StructureMap for dependency injection and I want to inject NHibernate sessions with it. I have the following code:

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 th开发者_开发知识库emselves?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消