Defining Your Own Merge Strategy

A merge strategy is a class that implements the CodeSmith.Engine.IMergeStrategy interface. The interface has two methods:

Method What it does
void Init(string init) Receives the initialization string (the mergeInit value), so your strategy can read its settings.
string Merge(MergeContext context) Merges the template output with the existing content and returns the content to write.

MergeContext gives you everything you need for the merge:

Property Contents
SourceContent The existing content of the output file.
OutputContent The content the template generated.
OutputFile The output file being written.
Template The template that generated the output.

The simplest possible merge strategy ignores the existing content and returns the template output:

public string Merge(CodeSmith.Engine.MergeContext context)
{
    return context.OutputContent;
}

Tip

CodeSmith.Engine.StringUtil.ParseConfigString(init) splits an initialization string into a dictionary of settings, the same way the built-in merge strategies do.

Using your merge strategy

Compile your merge strategy into an assembly. You can then use it in either of these ways:

  • Set mergeType to the type's fully qualified name, including the assembly name:

    <propertySet name="Sample" output="Sample.cs" template="Sample.cst"
                 mergeType="MyNamespace.MyMergeStrategy, MyMergeAssembly"
                 mergeInit="MergeParameters=Sample Merge Parameters;Language=C#" />
    
  • Register an alias for it, and use the alias as the mergeType, just like the built-in InsertRegion and PreserveRegions aliases.

Registering an alias

An alias lets you refer to your merge strategy by name instead of by its full type name. To add one:

  1. Open the Options dialog and select the Engine page.
  2. In the Merge category, open the MergeStrategyAliases collection.
  3. Add an entry, and set its Name to the alias and its TypeName to the fully qualified type name.

Generator stores the aliases in the registry, under HKEY_CURRENT_USER\Software\CodeSmith\v8.5\MergeStrategyAlias. Each alias is a numbered subkey with Name and TypeName string values. For example, this is the entry for the built-in PreserveRegions merge strategy, as a registry export:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\CodeSmith\v8.5\MergeStrategyAlias\2]
"Name"="PreserveRegions"
"TypeName"="CodeSmith.Engine.PreserveRegionsMergeStrategy,CodeSmith.Engine"

If you add an alias in the registry directly, use a subkey number that isn't already taken.