I have an interface.
public interface ISomeInterface {...}
and two implementations (SomeImpl1 and SomeImpl2):
public class
If you can switch from constructor injection to property injection, and let both services derive from the same base class (or implement the same interface), you can do the following:
builder.RegisterType().OnActivating(e =>
{
var type = e.Instance.GetType();
// get ISomeInterface based on instance type, i.e.:
ISomeInterface dependency =
e.Context.ResolveNamed(type.Name);
e.Instance.SomeInterface = dependency;
});
For this to work you need to define the property on the base type (or interface). This solution is very flexible and would even allow you to complex things such as injecting a generic type, based on the parent type, as can be see below:
builder.RegisterType().OnActivating(e =>
{
var type =
typeof(GenericImpl<>).MakeGenericType(e.Instance.GetType());
e.Instance.SomeInterface = (ISomeInterface)e.Context.Resolve(type);
});
This approach has a few downsides:
On the upside, this design is simple and works for almost any container.