I have an interface.
public interface ISomeInterface {...}
and two implementations (SomeImpl1 and SomeImpl2):
public class
Autofac supports identification of services by name. Using this, you can register your implementations with a name (using the Named
extension method). You can then resolve them by name in the IServiceX registration delegates, using the ResolveNamed
extension method. The following code demonstrates this.
var cb = new ContainerBuilder();
cb.Register(c => new SomeImpl1()).Named("impl1");
cb.Register(c => new SomeImpl2()).Named("impl2");
cb.Register(c => new Service1(c.ResolveNamed("impl1"))).As();
cb.Register(c => new Service2(c.ResolveNamed("impl2"))).As();
var container = cb.Build();
var s1 = container.Resolve();//Contains impl1
var s2 = container.Resolve();//Contains impl2
Alternative using RegisterType
(as opposed to Register
)
You can achieve the same result using the RegisterType
extension method in combination with WithParameter
and ResolvedParameter
. 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:
var cb = new ContainerBuilder();
cb.RegisterType().Named("impl1");
cb.RegisterType().Named("impl2");
cb.RegisterType().As().WithParameter(ResolvedParameter.ForNamed("impl1"));
cb.RegisterType().As().WithParameter(ResolvedParameter.ForNamed("impl2"));
var container = cb.Build();
var s1 = container.Resolve();//Contains impl1
var s2 = container.Resolve();//Contains impl2