Named singleton instance in StructureMap (Multiple

2019-05-06 02:16发布

问题:

I have a scenario where I have two Nhibernate SessionFactorys I need to register an use with StructureMap. Only Foo needs mySessionFactory sessions.

Like this:

For<ISessionFactory>().Singleton().Use(NHibernateConfiguration.GetDefaultSessionFactory());
For<ISession>().HybridHttpOrThreadLocalScoped().Use(x => x.GetInstance<ISessionFactory>().OpenSession());
For<ISessionFactory>().Singleton().Use(AnotherNHibernateConfiguration.GetDefaultSessionFactory).Named("mySessionFactory");
For<ISession>().HybridHttpOrThreadLocalScoped().Use(x => x.GetInstance<ISessionFactory>("mySessionFactory").OpenSession()).Named("mySession");

For<Foo>()
   .Use<Foo>()
   .Ctor<ISession>("session").Is(x => x.TheInstanceNamed("mySession"));

The problem is that mySessionFactory is now used everywhere when I only wanted to to be used in Foo and everywhere else should use my unnamed instance.

What I'm I doing wrong?

回答1:

On both your named instances, change Use to Add. Use sets that instance as the default as well as adding it as an instance. You could also reverse the order of your config (the last instance of a type added with Use will become the default), but using the Add method is much more explicit.