dimanche 24 avril 2016

Find which methods an object is used in using reflection

Given a single assembly, is there a way to find out how many times and from where a particular class is called? Example:

// CustomDbContext: Entity Framework DbContext
var type = typeof(CustomDbContext);

var types = typeof(CustomDbContext)
    .Assembly
    .GetTypes()
    .Where(t => t != typeof(CustomDbContext))
    .ToList();

foreach (var type in types)
{
    var methodInfos = type
        .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
        .ToList();

    foreach (var methodInfo in methodInfos)
    {
        var methodBody = methodInfo.GetMethodBody();

        // Is it possible to determine whether the [CustomDbContext] class has been instantiated or referred to?
    }
}

I know this is possible when analyzing code (say using Roslyn), but I'm interested in finding out if we can get this info from a compiled assembly.





Aucun commentaire:

Enregistrer un commentaire