asyncapi

Modelina Csharp Generator Add Inheritance


I am playing around with asyncapi/modelina CSharpGenerator. I would like to add inheritance to the generated class something like this

 public class UserCreated: IEvent
    {
      
    }

Is that possible? Can we add additional dependencies other than the generated ones?


Solution

  • Inheritance is, unfortunately, one of those features that have gotten put on the backburner, and still is.

    Fortunately, it is possible to accomplish it, but it does require you to overwrite the entire rendering behavior, which might not be maintainable in the long run. You can find the full example in this PR: https://github.com/asyncapi/modelina/pull/772

    const generator = new CSharpGenerator({
      presets: [
        {
          class: {
            // Self is used to overwrite the entire rendering behavior of the class
            self: async ({renderer, options, model}) => {
              //Render all the class content
              const content = [
                await renderer.renderProperties(),
                await renderer.runCtorPreset(),
                await renderer.renderAccessors(),
                await renderer.runAdditionalContentPreset(),
              ];
    
              if (options?.collectionType === 'List' ||
                model.additionalProperties !== undefined ||
                model.patternProperties !== undefined) {
                renderer.addDependency('using System.Collections.Generic;');
              }
    
              const formattedName = renderer.nameType(model.$id);
              return `public class ${formattedName} : IEvent
    {
    ${renderer.indent(renderer.renderBlock(content, 2))}
    }`;
            }
          }
        }
      ]
    });
    

    What is happening here is that we create a custom preset for the class renderer and overwrite the entire rendering process of itself.

    This will generate based on this input:

    public class Root : IEvent
    {
      private string[] email;
      public string[] Email 
      {
        get { return email; }
        set { email = value; }
      }
    }
    

    Regarding dependencies, please see https://github.com/asyncapi/modelina/blob/master/docs/presets.md#adding-new-dependencies. You can do this in the self preset hook.

    You can read more about the presets here: https://github.com/asyncapi/modelina/blob/master/docs/presets.md