I\'m using Microsoft Unity. I have an interface ICustomerService and its implementation CustomerService. I can register them for the Unity containe
You can use containers hierarchy. Register common implementation in parent container, this instance will resolve if resolved through master container. Then create child container, and register alternative implementation in child container. This implementation will resolve If resolved through child container, i.e. registration in child container overrides registration in parent container.
Here's the example:
public interface IService {}
public interface IOtherService {}
// Standard implementation of IService
public class StandardService : IService {}
// Alternative implementaion of IService
public class SpecialService : IService {}
public class OtherService : IOtherService {}
public class Consumer
{
public Consumer(IService service, IOtherService otherService)
{}
}
private void Test()
{
IUnityContainer parent = new UnityContainer()
.RegisterType()
.RegisterType();
// Here standardWay is initialized with StandardService as IService and OtherService as IOtherService
Consumer standardWay = parent.Resolve();
// We construct child container and override IService registration
IUnityContainer child = parent.CreateChildContainer()
.RegisterType();
// And here specialWay is initialized with SpecialService as IService and still OtherService as IOtherService
Consumer specialWay = child.Resolve();
// Profit!
}
Please note that using containers hierarchy you can know nothing about number of parameters in constructor, and that's great, because as long as you are bound to parameters count and their types you can't use full power of IoC. The less you know the better.