I have an interface.
public interface ISomeInterface {...}
and two implementations (SomeImpl1 and SomeImpl2):
public class SomeImpl1 : ISomeInterface {...}
public class SomeImpl2 : ISomeInterface {...}
I also have two services where I inject ISomeInterface (via contructor):
public class Service1 : IService1
{
public Service1(ISomeInterface someInterface)
{
}
...
}
and
public class Service2 : IService2
{
public Service2(ISomeInterface someInterface)
{
}
...
}
I’m using Autofac as my IoC tool.
The question. How can I configure Autofac registrations so SomeImpl1 will be automatically injected into Service1, and SomeImpl2 will be automatically injected into Service2.
Thank you!
Autofac supports identification of services by name. Using this, you can register your implementations with a name (using the
Namedextension method). You can then resolve them by name in the IServiceX registration delegates, using theResolveNamedextension method. The following code demonstrates this.Alternative using
RegisterType(as opposed toRegister)You can achieve the same result using the
RegisterTypeextension method in combination withWithParameterandResolvedParameter. This is useful if the constructor taking a named parameter also takes other non-named parameters that you don’t care to specify in a registration delegate: