Skip to content

Instantly share code, notes, and snippets.

@bmeredith
Created July 23, 2020 19:15
Show Gist options
  • Save bmeredith/0cfdf00f0b5d71c6cf248106ae47e165 to your computer and use it in GitHub Desktop.
Save bmeredith/0cfdf00f0b5d71c6cf248106ae47e165 to your computer and use it in GitHub Desktop.
Autofac Keyed Services
public class MyController : ControllerBase
{
private readonly Func<int, IService> _serviceFactory;
public MyController(Func<int, IService> serviceFactory)
{
_serviceFactory = serviceFactory;
}
public ActionResult<string> GetSomething()
{
var v1Service = _serviceFactory(1);
var result = service.GetSomething();
return result;
}
}
var builder = new ContainerBuilder();
builder.RegisterType<V1Service>()
.As<IService>().Keyed<IService>(1);
builder.RegisterType<V2Service>()
.As<IService>().Keyed<IService>(2);
builder.Register<Func<int, IService>>(c =>
{
var componentContext = c.Resolve<IComponentContext>();
return (version) =>
{
var dataService = componentContext.ResolveKeyed<IService>(version);
return dataService;
};
});
return builder.Build();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment