I have a controller that accepts some dependency as a constructor argument:
public class AccountsController : ApiController
{
public AccountsController(IAccountsService accountService)
{
this.accountService = accountService;
}
// actions
}
public interface IAccountsService
{
IEnumerable<AccountDto> GetAccounts(string userName);
}
To resolve this dependency I use Unity.WebApi package:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// other configuration
config.DependencyResolver = new UnityDependencyResolver(myContainer);
}
}
I have two different implementations of IAccountsService and I'd like to expose both of them using the same controller class. From the routing perspective, I'd like to use different controller-level paths and the same underlying path structure for actions and parameters.
My way is to inherit two controllers from AccountsController and register them in UnityContainer to use different IAccountsService implementations.
public class Accounts1Controller : AccountsController
{
public Accounts1Controller([Dependency("Service1")]IAccountsService accountService) :
base(accountService) { }
}
public class Accounts2Controller : AccountsController
{
public Accounts2Controller([Dependency("Service2")]IAccountsService accountService) :
base(accountService) { }
}
Is there a more straightforward way to do this?
I'd prefer to make the controller(s) container-unaware and to avoid the redundant inheritance (regardless to DI framework - Unity is not a single option).
IAccountsServiceas a data source. I'm going to make same web APIs for both implementations ofIAccountsService. The set of actions is the same for both implementations.Proxydesign pattern. TheProxyclass would have both the implementations ofIAccountsServiceand it resolves which one to be used. To DI framework you would give the implementation ofProxyclass.