vendredi 17 avril 2020

How does .NET Core DI determine unspecified generic parameter like ILogger?

(This question on ILogger is resolved in this question. My question asks how the DI system accomplishes it)

I was curious how .NET Core ILogger<MyClass> could be resolved for any type of MyClass. I checked the source code and found this one:

services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>)));

So I understand that, when I need ILogger<MyClass>, the DI will automatically create a Logger<MyClass>. My question is, from Reflection, how does it happen? I made this code to investigate:

        var t1 = typeof(IList<>);
        Console.WriteLine(t1.FullName); // System.Collections.Generic.IList`1
        Console.WriteLine(t1.IsGenericType); // True
        Console.WriteLine(t1.GetGenericArguments()[0].Name); // T
        Console.WriteLine(t1.GetGenericArguments()[0].FullName); // null

        var t2 = typeof(IList<int>);
        Console.WriteLine(t2.FullName); // System.Collections.Generic.IList`1...
        Console.WriteLine(t2.IsGenericType); // True
        Console.WriteLine(t2.GetGenericArguments()[0].Name); // Int32
        Console.WriteLine(t2.GetGenericArguments()[0].FullName); // System.Int32

Weirdly enough, t1 still has valid GetGenericArguments() result with the type being T (and null FullName). Is that how the DI implementation check if the input type is Something<>?





Aucun commentaire:

Enregistrer un commentaire