Last active
April 27, 2024 16:25
-
-
Save gurustron/2fe50ff8a6173b431fae66e211082f1e to your computer and use it in GitHub Desktop.
Autofac keyed registration with Func<> factory resolve
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<ImplOne>() | |
.Keyed<IDependency>(MyTypeEnum.TypeOne) | |
.SingleInstance(); | |
builder.RegisterType<ImplTwo>() | |
.Keyed<IDependency>(MyTypeEnum.TypeTwo) | |
.SingleInstance(); | |
// here is the main trick | |
builder.Register((c, p) => | |
{ | |
var type = p.TypedAs<MyTypeEnum>(); | |
var resolve = c.Resolve<IIndex<MyTypeEnum, IDependency>>(); | |
return resolve[type]; | |
}); | |
var container = builder.Build(); | |
var factory = container.Resolve<Func<MyTypeEnum, IDependency>>(); | |
var dependency = factory(MyTypeEnum.TypeTwo); | |
public class ImplOne : IDependency {} | |
public class ImplTwo : IDependency {} | |
public interface IDependency{} | |
public enum MyTypeEnum | |
{ | |
TypeOne, | |
TypeTwo | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Create
Func<TKey, TDep>
factory using Autofac keyed registrations.