简体   繁体   中英

GetMethod to get Dispose(bool disposing) dynamically

I am currently trying to implement a class that uses TypeBuilder to dynamically create a new class that derives from a class that itself derives from DbContext (iow the dynamic class indirectly inherits from DbContext ).

To override (with DefineMethod + DefineMethodOverride ) the Dispose class I need to retrieve it first using GetMethod . I was able to retrieve the SaveChanges() method by using the following:

typeof(TBaseDbContext).GetMethod("SaveChanges")

However the Dispose(bool disposing) is quite different in that it is protected and has arguments.

Narrowing down on the problem I came to the following code:

        MethodInfo disposeOfBase =
            typeof(DbContext).GetMethod("Dispose",
                BindingFlags.NonPublic,
                null,
                CallingConventions.Any,
                new Type[] { typeof(bool) },
                null);

The result in disposeOfBase is null. I have tried different combinations but I think the above should be near to correct. I have no idea why the Dispose is not found.

What am I doing wrong here? How can I modify the code so that disposeOfBase holds the info of the protected Dispose method of DbContext ?

I tested and it worked, so I'm posting the above comment as an answer:

Try BindingFlags.NonPublic | BindingFlags.Instance BindingFlags.NonPublic | BindingFlags.Instance . You must specify either Instance or Static to get a method back .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM