Jeff
Jeff

Reputation: 12183

How can I get Unity Container to cascade the registration name down the chain?

Consider the following:

public class MyService : IService {
  public MyService(IDbSession session) {}
}


// Service used both by controller and background work.
container.RegisterType<IService, MyService>(new TransientLifetimeManager());

// Database session when used from a controller
container.RegisterType<IDbSession, DbSession>(new PerRequestLifetimeManager());
// Database session as used when doing background work
container.RegisterType<IDbSession, DbSession>("BackgroundWork", new TransientLifetimeManager());



// At run-time I expect the named resolution to be "cascading" down to the IDbSession named registration.
container.Resolve<IService>("BackgroundWork");

I'd like to resolve the IDbSession with the "BackgroundWork" name, since the IService is being resolved with that name.

Unity does not do this unless I manually specify the constructor parameters in an InjectionConstructor, which is not that intuitive. I'd have to keep that updated as the signature of my service changes.

How can I do this in the least painless way?

The idea is that when doing background work, my Db session must be managed by the class doing the background work, not the request.

Upvotes: 1

Views: 1498

Answers (1)

jlvaquero
jlvaquero

Reputation: 8785

You can use child container.

 IUnityContainer container = new UnityContainer();
 container.RegisterType<IService, MyService>(new TransientLifetimeManager());
 container.RegisterType<IDbSession, DBSession>(new PerRequestLifetimeManager());

 IUnityContainer childContainer = container.CreateChildContainer();
 childContainer.RegisterType<IDbSession, DBSession>(new TransientLifetimeManager());

 IService parentService = container.Resolve<IService>();
 IService parentService2 = container.Resolve<IService>();
 IService childService = childContainer.Resolve<IService>();
IService childService2 = childContainer.Resolve<IService>();

Inmed Window:

?parentService.GetHashCode()
45653674
?parentService2.GetHashCode()
41149443
//one service instance per resolve
?parentService.session.GetHashCode()
39785641
?parentService2.session.GetHashCode()
39785641
//same DBSesion in every service resolved per HTTP request
?childService.GetHashCode()
45523402
?childService.session.GetHashCode()
35287174
//new Service and DbSession per resolve
?childService2.GetHashCode()
44419000
?childService2.session.GetHashCode()
52697953

Upvotes: 1

Related Questions