Random thoughts about everything and nothing

Archive for the ‘CodeSmith’ Category

Compiling CodeSmith templates to assemblies

leave a comment »


There’s an option in CodeSmith studio to compile your template to an assembly.  This has some advantages over the “normal” way of working like referencing the template in a project, no compilation time when running…

You can find the option under Tools | Compile To Assembly


Fill texboxes in the Compile To Assembly window, being:

  • Assembly Name: Output filepath
  • Namespace:  Namespace in which the template class will be placed
  • Type Name:  Class name of the template


Press OK to start the compilation.

Using the Codesmith API

Another way to compile your templates is to use the CodeSmith API.  The  CodeSmith.Engine dll contains the CodeTemplateCompile class, which exposes the same properties  as the CodeSmith Studio variant.  Take a look at the following snippet:

            string templatePath = @"C:outputCompileThis.cst";
            string outputNamespace = "Demo.CodeSmith.Templates";
            string outputTypeName = "CompileThis";
            string outputAssembly = @"c:outputCompileThis.dll";
            CodeTemplateCompiler compiler = new CodeTemplateCompiler(templatePath);
            compiler.Namespace = outputNamespace;
            compiler.TypeName = outputTypeName;
            compiler.Compile(outputAssembly, true);
            Console.WriteLine("#Errors: {0}", compiler.Errors.Count);
            if (compiler.Errors.Count > 0)

Watch out

No matter how you compile your templates, there are some things you should keep in mind:

  1. More than ones i needed to restart CodeSmith Studio (or use unlocker) when recompiling the template, i.e. a lock might held by CodeSmith Studio
  2. Any dependencies you have in the template must be placed in the ouput directory (except for the typical framework dll’s and the ones placed in the GAC) 

Written by Michael

June 22, 2007 at 9:53 pm

Posted in .NET, CodeSmith