samedi 17 juillet 2021

Use reflection to find IConfigureOptions

I want to find all types that implement ASP.NET Core's IConfigureOptions<JsonOptions> interface.

Here is an example of such a class:

public sealed class MyJsonOptions : IConfigureOptions<JsonOptions> {
  public void Configure(JsonOptions options) { }
}

This found nothing:

AppDomain.CurrentDomain
.GetAssemblies()
.Where(assembly => !assembly.IsDynamic)
.SelectMany(assembly => assembly.ExportedTypes)
.Where(type => type.IsAssignableTo<IConfigureOptions<JsonOptions>>())
.ToArray();

I also tried this:

AppDomain.CurrentDomain
.GetAssemblies()
.Where(assembly => !assembly.IsDynamic)
.SelectMany(assembly => assembly.ExportedTypes)
.Where(type => type
  .GetInterfaces()
  .Any(x =>
    x.IsGenericType &&
    x.GetGenericTypeDefinition() == typeof(IConfigureOptions<>)))
    //&& x.GetGenericArguments()[0] == typeof(JsonOptions)  // if included then nothing found
.ToArray();

That gives me all types implementing IConfigureOptions<>. But of course I also need the typeparam JsonOptions.

How do I do this?





Aucun commentaire:

Enregistrer un commentaire