Created
July 23, 2020 19:15
-
-
Save bmeredith/0cfdf00f0b5d71c6cf248106ae47e165 to your computer and use it in GitHub Desktop.
Autofac Keyed Services
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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