1
votes

i'm using unity to resolve an object graph.

public interface ISessionManager
{
}

public class DefaultSessionManager : ISessionManager
{
}

public class OnCallSessionManager : ISessionManager
{
}

And i have service class that utilize ISessionManager on constructor

public class CustomerService
{
    public class CustomerService(ISessionManager sessionManager)
    {
    }
}

On top of object graph. I have a viewmodel class and a data manager class.

public class ViewModel(CustomerService customerService)
{
}

public class DataManager(CustomerService customerService)
{
}

Now i want to resolve ViewModel and DataManager using different ISessionManager. For ViewModel class i want DefaultSessionManager and OnCallSessionManager for DataManager. How can i do that ?

Thanks in advance.

1

1 Answers

1
votes

Using configuration in code you can register something like this:

var container = new UnityContainer();

container.RegisterType<ISessionManager, DefaultSessionManager>()
  .RegisterType<ISessionManager, OnCallSessionManager>("oncall")
  .RegisterType<CustomerService>()
  .RegisterType<CustomerService>(
    "oncall",
    new InjectionConstructor(
      new ResolvedParameter(
        typeof(ISessionManager),
        "oncall")))
  .RegisterType<ViewModel>()
  .RegisterType<DataManager>(
    new InjectionConstructor(
      new ResolvedParameter(
        typeof(CustomerService),
        "oncall")));

Its ugly as hell but it should do the trick.