You can generate the code using T4 templates. For example, create this XML file and place it in your bin folder:
<?xml version="1.0" encoding="utf-8" ?>
<command>
<name>NameCommand</name>
<param>Car</param>
</command>
Now add a new item to your project:
- Right click project node in solution explorer > Add > New Item > Visual C# Items and select Text Template.
- Give your template a name. I called it ICommandGenerator.
In the template place the following code:
<#@ output extension=".cs" #>
<#@ assembly name="System.Xml"#>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System" #>
<#@ template debug="false" hostspecific="true" language="C#" #>
<#
XmlDocument doc = new XmlDocument();
// Replace this file path with yours:
doc.Load(Host.ResolvePath(@"bin\debug\NameCommand.xml"));
var className = doc.GetElementsByTagName("name")[0].InnerText;
var paramName = doc.GetElementsByTagName("param")[0].InnerText;
#>
namespace ConsoleApplication1
{
public partial class <#= className #>
{
public <#= className #>() {}
public void Execute(<#= paramName #> p)
{
// your code here...
}
}
}
Right click on the TT file in solution explorer and select Run Custom Tool. It will generate the class below using the XML file. This class will be a child node of the TT file so expand the TT file and you will see this class:
namespace ConsoleApplication1
{
public partial class NameCommand
{
public NameCommand() {}
public void Execute(Car p)
{
// your code here...
}
}
}
You can modify the TT file to use another namespace instead of the ConsoleApplication
. You can even put a bunch of Command
types in the XML file and loop through all of them and generate many classes. You can read more about T4 templates here.
This is how EF generates classes using database first technique wherein you instruct EF by pointing it towards a database using a connection string. EF then analyses your database and eventually places a .tt in your project.