简体   繁体   English

如何确定接口上哪个类称为公共方法?

[英]How can I determine which class called a public method on an interface?

I am working on a project that relies heavily on NServiceBus. 我正在从事一个严重依赖NServiceBus的项目。 Unfortunately it has gotten a bit messy, and even though it is written in C#, there is some chaos to it. 不幸的是,它变得有些混乱,即使它是用C#编写的,也有些混乱。 For example I have Bus.Publish(A) somewhere, then elsewhere is public AHandler : IHandleMessages<A> which may be fine but since this is a P/S pattern there are often multiple handlers. 例如,我在某处有Bus.Publish(A) ,然后在其他地方有public AHandler : IHandleMessages<A>可能很好,但是由于这是一种P / S模式,因此通常有多个处理程序。 There is some intrinsic need to memorize the project and it is difficult for new developers to follow the flow of code. 记住项目有一些内在的需求,新开发者很难遵循代码流。

My solution to this was to create a console app, or perhaps some sort of UI, that would use reflection to scan the assembly and draw a map of my project for me. 我对此的解决方案是创建一个控制台应用程序或某种UI,该应用程序将使用反射来扫描程序集并为我绘制项目图。 So far I've been able to effectively pick up all of the public class _Handler : IHandleMessages<_> which is great, but now I need to determine where the messages are originating from. 到目前为止,我已经能够有效地选择所有public class _Handler : IHandleMessages<_> ,这很不错,但是现在我需要确定消息的来源。

In particular, I am wondering if there is a way using reflection to determine within which classes Bus.Publish(_) is being called (Bus is actually an instance of IBus). 特别是,我想知道是否有一种方法可以使用反射来确定在哪个类中Bus.Publish(_) (Bus实际上是IBus的一个实例)。 For isntance if public void Handler(A a) { Bus.Publish(B) } I want to know the argument passed into Bus.Publish() (so B) and also the name of the class that contains this handler. 对于非public void Handler(A a) { Bus.Publish(B) }我想知道传递给Bus.Publish()的参数(所以B)以及包含此处理程序的类的名称。

Don't know if this will help - hopefully it will. 不知道这是否会有所帮助-希望会有所帮助。

I have a requirement to find the origin of a call to a piece of code - an Audit Listener so we can log the component used to apply the changes. 我需要找到对一段代码的调用的源-审计监听器,以便我们可以记录用于应用更改的组件。 My code is as follows: 我的代码如下:

Assembly currentAssembly = Assembly.GetExecutingAssembly();

string initialAssembly = new StackTrace().GetFrames()
                                         .Where(x => x.GetMethod().ReflectedType != null)
                                         .Select(x => x.GetMethod().ReflectedType.Assembly).Distinct()
                                         .Where(x => x.GetReferencedAssemblies().Any(y => y.FullName == currentAssembly.FullName))
                                         .Last()
                                         .FullName;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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