5

I'm looking at Creating my own addin for Cake to extend the DSL, documentation's a bit lacking.

What's the bare minimum needed for creating an Cake addin script alias?

devlead
  • 4,935
  • 15
  • 36

1 Answers1

5

An addin is just an regular .NET Assembly packaged as an NuGet package, as a matter of fact in general you can reference almost any .NET assembly.

What an alias adds beyond regular assembly:

  • Adds methods to the Cake DSL making it available globally in Cake scripts
  • Namespace imports (can make types available without need of using statement)
  • Access to Cake Core classes/features

A minimal alias implementation would be an extension method that extends Cake.Core.ICakeContext which has the Cake.Core.Annotations.CakeAlias attribute.

So a minimal implementation would be, create an .NET assembly, add a reference to the Cake.Core nuget package and add a class like below:

public static class HelloWorldAliases
{
        [CakeMethodAlias]
        public static void HelloWorld(this ICakeContext context)
        {
             context.Log.Information("Hello {0}", "World");
        }
}

To test your alias you can load your assembly via the #reference directive or if you packaged it via the #addin directive.
You can then call your alias in a script using HelloWorld() the ICakeContext can be omitted as it's automatically provided by the Cake core engine.

Example "HelloWorld" Cake script:

#reference "HelloWorld.dll"
HelloWorld();

If you have any namespaces you want to automatically import for the user, then you do that using the CakeNamespaceImport attribute to your extension method, example:

public static class HelloWorldAliases
{
        [CakeMethodAlias]
        [CakeNamespaceImport("MyNameSpace.Common")]
        public static void HelloWorld(this ICakeContext context)
        {
             context.Log.Information("Hello {0}", "World");
        }
}

Any type in MyNameSpace.Common will now be made available without the need to add a using MyNameSpace.Common to the script.

Once you’ve packaged your addin and published to nuget, then you can reference it by package id using the #addin directive, example:

#addin "HelloWorld"
HelloWorld();
devlead
  • 4,935
  • 15
  • 36