Question

I have a projet in c# .net.
I need to hook the "pre build" event so I can run a c# class that will generate other c# class to the same project.
I know that in java you can generate source code using maven plugin, is it possible in .net?

Thanks.

Was it helpful?

Solution

There are at least two options:

  1. Use T4
  2. Add a pre-build step to the build file.

T4 is the inbuilt way to do code generation (and widely used in ASP.NET MVC scaffolding and Entity Framework type generation). However T4 doesn't directly support compile time generation. It does either design time – with the developer triggering (re-)generation – or runtime generation; (third party tools can add compile time generation).


Adendum (after 6 years): NuGet packages like Clarius.TransformOnBuild can also do this.

A custom MSBuild task (including running an external program) can be used to create code which is then included in the compile. In the simplest cases the "pre-build" setting of a project can be used (the Build Events tab of the project properties). Directly working in MSBuild (and a .csproj is a MSBuild file) gives more flexibility.

OTHER TIPS

Try the Tangible T4 Editor. Its a plugin for Visual Studio that exposes the built in T4 Text Template functionality so you can use it to auto-generate C# files. It enables support for compile time generation of C# code within Visual Studio.

I used this to convert a .xml file into 2,600 lines of C# at compile time. Now, if I change the .xml file, and recompile, it will automatically regenerate the correct C# code.

It works like magic, and is completely seamless.

Sounds like you want T4 Templates.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top