Skip to content

Instantly share code, notes, and snippets.

@graffic
Created May 24, 2019 10:38
Show Gist options
  • Save graffic/f7f91eed5ea2a4ca54c1f20cd4fa6e10 to your computer and use it in GitHub Desktop.
Save graffic/f7f91eed5ea2a4ca54c1f20cd4fa6e10 to your computer and use it in GitHub Desktop.
Failed attempt to register all DBSets
public class AutofacModule:Module
{
private static readonly object[] NoParameters = new object[] { };
protected override void Load(ContainerBuilder builder)
{
var dbsetType = typeof(DbSet<>);
var registerMethod = new Func<ContainerBuilder, Func<IComponentContext, object>, IRegistrationBuilder<object, SimpleActivatorData, SingleRegistrationStyle>>(Af.RegistrationExtensions.Register<object>)
.Method.GetGenericMethodDefinition();
foreach (var property in typeof(ApplicationDbContext).GetProperties())
{
var getMethod = property.GetMethod;
var returnType = getMethod.ReturnType;
if (!returnType.IsGenericType || returnType.GetGenericTypeDefinition() != dbsetType)
{
continue;
}
// When this gets called, getMethod is null :?
T getCaller<T>(IComponentContext c) => (T)getMethod.Invoke(c.Resolve<ApplicationDbContext>(), parameters: NoParameters);
var factory = new Func<IComponentContext, object>(getCaller<object>).Method.GetGenericMethodDefinition();
var genericMethod = factory.MakeGenericMethod(returnType);
var theDelegate = Delegate.CreateDelegate(Expression.GetDelegateType(new[] { typeof(IComponentContext), returnType }), null, genericMethod);
var registered = (IRegistrationBuilder<object, SimpleActivatorData, SingleRegistrationStyle>)registerMethod.MakeGenericMethod(returnType).Invoke(null, new object[] { builder, theDelegate });
// As<IDbSet<entity>()
var entityType = returnType.GenericTypeArguments[0];
var iDbSetType = typeof(IDbSet<>).MakeGenericType(entityType);
registered.As(iDbSetType);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment