0

Like the below code, an interface with the OperationContract attribute, I want to create another interface that inherits IPCClient but without the OperationContract attribute. In runtime, add the attribute to all methods of inherited interface or class while "initialize method" is called.

    public interface IPCClient
    {
        [OperationContract]
        void Event(string eventitem);

        [OperationContract]
        void Message(string msg);

        [OperationContract]
        ComponentCmdResponse Command(ComponentCmd cmd);
    }
  • You can't add an attribute at runtime. However, you can use a slightly different but related system: [`TypeDescriptors`](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.typedescriptor?view=net-6.0). You read attributes using `TypeDescriptor.GetAttributes` (rather than `Type.GetAttributes`), and this will also return attributes registered at runtime with `TypeDescriptor.AddAttributes`. (Attributes added with `TypeDescriptor.AddAttributes` can only be read by `TypeDescriptor.GetAttributes`, and not by `Type.GetAttributes`) – canton7 May 25 '22 at 10:29
  • That said, I don't know whether it's possible to handle attributes on methods with `TypeDescriptor` – canton7 May 25 '22 at 10:30
  • I would suggest looking into [source generators](https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/source-generators-overview) which can generate code dynamically during the build. – NightOwl888 May 25 '22 at 10:34
  • thanks, @canton7, but [TypeDescriptor cannot inspect of method](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.typedescriptor?view=net-6.0#:~:text=In%20contrast%2C%20TypeDescriptor%20is%20an%20extensible%20inspection%20mechanism%20for%20components%3A%20those%20classes%20that%20implement%20the%20IComponent%20interface.%20Unlike%20reflection%2C%20it%20does%20not%20inspect%20for%20methods.) – zhongxiang qian May 25 '22 at 12:49
  • Is there any way to config WCF not using OperationContract Attribute? – zhongxiang qian May 25 '22 at 12:57
  • @NightOwl888 source generator is a good idea, I will try it during waiting for a good answer. – zhongxiang qian May 25 '22 at 13:05
  • You can check out these posts hope they are helpful to you.https://stackoverflow.com/questions/268426/how-do-i-add-attributes-to-a-method-at-runtime and https://stackoverflow.com/questions/129285/can-attributes-be-added-dynamically-in-c – Lan Huang May 26 '22 at 06:34

0 Answers0