How do I add attributes to a method at runtime?

人盡茶涼 提交于 2019-12-02 17:41:59

What you are trying to achieve is quite complicated, so I will try to provide something just to get you started. This is what I think you would need to combine in order to achieve something:

  1. Define an abstract class AbstractEventDebugger, with a method Search that searches all of the event members, and registers them with the EventInspector. Also, define a method IdentifyEvent that will allow you to identify the event that has called it (this depends on you - what parameters will have, etc.).
  2. Define a dynamic type using TypeBuilder (as described here), that inherits from your class. This class would be the class of your debugger object.
  3. Attach the Handlers to your class using Reflection.Emit.MethodBuilder (see here), which will be calling the IdentifyEvent method from the parent class and,
  4. Reflection.Emit the attributes on the handlers using CustomAttributeBuilder class (see here).
  5. Create an instance of your dynamic class and send it to the EventInspector.
  6. Fire it up :)

Here is a sample on how to create a method that calls something (Actually it's the classic "Hello world").

You will need to do a lot of tweaking in order to get it done well, but you will learn a lot about reflection.

Good luck!

Attributes are a compile-time feature (unless you are dealing with ComponentModel - but I suspect it is using reflection). As such, you cannot add attributes at runtime. It would a similar question to "how do I add an extra method to a type at runtime?". In regular C# / .NET (pre-DLR), you can't.

You need to delve into the world of the DynamicMethod. However, as you need then to know MSIL, I really suggest you think hard about your architecture.

The EventInspector uses EventTopics (which are stored in the WorkItem) to do all the heavy lifting. Each EventTopic object has access to a TraceSource called

Microsoft.Practices.CompositeUI.EventBroker.EventTopic

Which you can enable in your app.config file like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.diagnostics>
        <switches>
            <add name="Microsoft.Practices.CompositeUI.EventBroker.EventTopic" value="All" />
        </switches>
    </system.diagnostics>
</configuration>

This should make plenty of useful messages get routed to your debug window in Visual Studio. If you want to go beyond the VS debug window you have plenty of options. I'd recommend checking out the following article:

Code Instrumentation with TraceSource My Persoanl Vade Mecum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!