c# - How do I configure multiple connection factories in Unity? -


i have 2 domains access though 2 application interfaces ia1, ia2, each use different repositories r1 , r2. repositories use interface lets them create nhibernate sessions, isimplesessionfactory.

if repositories shared database set them both using unity container:

var unity = new unitycontainer();  unity.registertype<isimplesessionfactory, nhibernatesessionfactory>(                 new containercontrolledlifetimemanager(), new injectionconstructor("connectiona"));  unity.registertype<ia1, a1>(); unity.registertype<r1>();  unity.registertype<ia2, a2>(); unity.registertype<r2>(); 

but don't share connection string, want this:

var unity = new unitycontainer();  var child1 = unity.createchildcontainer();  child1.registertype<isimplesessionfactory, nhibernatesessionfactory>(                 new containercontrolledlifetimemanager(), new injectionconstructor("connectiona"));  child1.registertype<ia1, a1>(); child1.registertype<r1>();  var child2 = unity.createchildcontainer();  child2.registertype<isimplesessionfactory, nhibernatesessionfactory>(                 new containercontrolledlifetimemanager(), new injectionconstructor("connectionb"));  child2.registertype<ia2, a2>(); child2.registertype<r2>(); 

my problem want resolve ia2 a1 class. ideally want have session factories in parent container. it's repositories r1 , r2 need different isimplesessionfactorys understand it ever fall parent if not resolved locally in child, if move parent won't find session factory.

if understood problem correctly, believe employ named registrations no need 2 separate interfaces:

  // first named registration   child1.registertype<isimplesessionfactory, nhibernatesessionfactory>(             new containercontrolledlifetimemanager(),              new injectionconstructor("connectiona"), "connectiona");    child1.registertype<ia1, a1>( new injectionconstructor( new resolvedparameter<isimplesessionfactory>("connectiona"));   child1.registertype<r1>( new injectionconstructor( new resolvedparameter<isimplesessionfactory>("connectiona") );    // same goes second one, create named registration    // under different name 

the trick here register ia1 , r1 (and ia2/r2 respectively) in way precisely point how parameter should resolved (resolvedparameter pointing named registration).

note injectionconstructor not usable if services' constructors have more parameters. in such case, use injectionfactories instead

  child1.registertype<ia1, a1>(       new injectionfactory( container =>           {              // arbitrarily complicated imperative code create instance              // first resolve isimplesessionfactory name               isimplesessionfactory factory =                  container.resolve<isimplesessionfactory>( "containera" );               // create a1               return new a1( factory, any, other, parameters, here );          }      ) ); 

Comments