Skip to content

Instantly share code, notes, and snippets.

@gurustron
Last active April 27, 2024 16:25
Show Gist options
  • Save gurustron/2fe50ff8a6173b431fae66e211082f1e to your computer and use it in GitHub Desktop.
Save gurustron/2fe50ff8a6173b431fae66e211082f1e to your computer and use it in GitHub Desktop.
Autofac keyed registration with Func<> factory resolve
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
}
@gurustron
Copy link
Author

Create Func<TKey, TDep> factory using Autofac keyed registrations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment