通过T4模板生成代码,运行时实现

关键代码段:Host

using Microsoft.VisualStudio.TextTemplating;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace CodeGenerate.EngineHost
{
public class TextTemplatingEngineHost : ITextTemplatingEngineHost, ITextTemplatingSessionHost
{
public List<string> LocalDlls { get; set; }
public List<string> Namespaces { get; set; }
/// <summary>
/// 模板文件
/// </summary>
public string TemplateFile { get; set; }
/// <summary>
/// 文件扩展名
/// </summary>
public string FileExtension { get; set; }
/// <summary>
/// 文件扩展名
/// </summary>
public Encoding FileEncoding { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public CompilerErrorCollection Errors { get; set; }
public IList<string> StandardAssemblyReferences
{
get
{
LocalDlls.Add(typeof(System.Uri).Assembly.Location);
return LocalDlls;
}
}
public IList<string> StandardImports
{
get
{
Namespaces.Add("System");
return Namespaces;
}
}
/// <summary>
/// 参数传递
/// </summary>
public ITextTemplatingSession Session { get; set; } public bool LoadIncludeText(string requestFileName, out string content, out string location)
{
content = System.String.Empty;
location = System.String.Empty;
if (File.Exists(requestFileName))
{
content = File.ReadAllText(requestFileName);
return true;
}
else
{
return false;
}
}
public object GetHostOption(string optionName)
{
object returnObject;
switch (optionName)
{
case "CacheAssemblies":
returnObject = true;
break;
default:
returnObject = null;
break;
}
return returnObject;
}
public string ResolveAssemblyReference(string assemblyReference)
{
if (File.Exists(assemblyReference))
{
return assemblyReference;
}
string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), assemblyReference);
if (File.Exists(candidate))
{
return candidate;
}
return "";
}
public Type ResolveDirectiveProcessor(string processorName)
{
if (string.Compare(processorName, "XYZ", StringComparison.OrdinalIgnoreCase) == )
{
//return typeof();
}
throw new Exception("Directive Processor not found");
}
public string ResolvePath(string fileName)
{
if (fileName == null)
{
throw new ArgumentNullException("the file name cannot be null");
}
if (File.Exists(fileName))
{
return fileName;
}
string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), fileName);
if (File.Exists(candidate))
{
return candidate;
}
return fileName;
}
public string ResolveParameterValue(string directiveId, string processorName, string parameterName)
{
if (directiveId == null)
{
throw new ArgumentNullException("the directiveId cannot be null");
}
if (processorName == null)
{
throw new ArgumentNullException("the processorName cannot be null");
}
if (parameterName == null)
{
throw new ArgumentNullException("the parameterName cannot be null");
}
return String.Empty;
}
public void SetFileExtension(string extension)
{
FileExtension = extension;
}
public void SetOutputEncoding(System.Text.Encoding encoding, bool fromOutputDirective)
{
FileEncoding = encoding;
}
public void LogErrors(CompilerErrorCollection errors)
{
Errors = errors;
}
public AppDomain ProvideTemplatingAppDomain(string content)
{
return AppDomain.CreateDomain("Generation App Domain");
} public ITextTemplatingSession CreateSession()
{
return this.Session;
}
}
}

Session

using Microsoft.VisualStudio.TextTemplating;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks; namespace CodeGenerate.EngineHost
{
[Serializable]
public class TextTemplatingSession : Dictionary<string, Object>, ITextTemplatingSession, ISerializable
{
public Guid Id { get;private set; } public TextTemplatingSession() : this(Guid.NewGuid())
{
} public TextTemplatingSession(Guid id)
{
this.Id = id;
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
public TextTemplatingSession(SerializationInfo info, StreamingContext context)
: base(info, context)
{
Id = (Guid)info.GetValue("Id", typeof(Guid));
} void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("Id", Id);
} public override bool Equals(object obj)
{
var o = obj as TextTemplatingSession;
return o != null && o.Equals(this);
} public bool Equals(ITextTemplatingSession other)
{
return other != null && other.Id == this.Id;
} public bool Equals(Guid other)
{
return other.Equals(Id);
}
}
}

入口

  string templateFileName = "Template/test.tt";
TextTemplatingEngineHost host = new TextTemplatingEngineHost();
Engine engine = new Engine();
//引入本地dll
host.LocalDlls = new List<string>() { AppDomain.CurrentDomain.BaseDirectory.ToString() + "Params.dll" };
//引入命名空间
host.Namespaces = new List<string>() { "Params" };
//模板文件
host.TemplateFile = templateFileName;
//设置输出文件的编码格式
host.SetOutputEncoding(System.Text.Encoding.UTF8, false);
//通过Session将参数传递到模板
EngineHost.TextTemplatingSession keyValuePairs = new EngineHost.TextTemplatingSession();
testType t = new testType() { Name = "" };
keyValuePairs.Add("test", t);
host.Session = keyValuePairs;
//模板
string input = File.ReadAllText(templateFileName);
//执行代码生成
string output = engine.ProcessTemplate(input, host);
//设置文件的输出路径和文件扩展名 ,,根据模板中的设置定义
string outputFileName = string.Concat(
AppDomain.CurrentDomain.BaseDirectory.ToString(), "Output/",
Path.GetFileNameWithoutExtension(templateFileName),
host.FileExtension);
//将生成的文件写入到新位置
File.WriteAllText(outputFileName, output, host.FileEncoding);
if (host.Errors.HasErrors)
{
foreach (CompilerError error in host.Errors)
{
MessageBox.Show(error.ToString());
}
}

tt文件

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ assembly name="Params.dll" #>
<#@ import namespace="Params" #>
<#@ parameter type="Params.testType" name="test" #>
<#@ output extension=".cs" #>
<# if(test!=null&&test.Name!=null){#>
<#=test.Name #>
<# } #>

自定义参数

 [Serializable]
public class testType
{
public string Name { get; set; }
}

C# 通过T4自动生成代码的更多相关文章

  1. mybatis generator maven插件自动生成代码

    如果你正为无聊Dao代码的编写感到苦恼,如果你正为怕一个单词拼错导致Dao操作失败而感到苦恼,那么就可以考虑一些Mybatis generator这个差价,它会帮我们自动生成代码,类似于Hiberna ...

  2. java如何在eclipse编译时自动生成代码

    用eclipse写java代码,自动编译时,如何能够触发一个动作,这个动作是生成本项目的代码,并且编译完成后,自动生成的代码也编译好了, java编辑器中就可以做到对新生成的代码的自动提示? 不生成代 ...

  3. MyBatis自动生成代码示例

    在项目中使用到mybatis时,都会选择自动生成实体类,Mapper,SqlMap这三个东东. 手头上在用的又不方便,找了下网上,其实有很多文章,但有些引用外部文件时不成功,也不方便,所以重新整理了下 ...

  4. MyBatis使用Generator自动生成代码

    MyBatis中,可以使用Generator自动生成代码,包括DAO层. MODEL层 .MAPPING SQL映射文件. 第一步: 配置好自动生成代码所需的XML配置文件,例如(generator. ...

  5. mybatis 自动生成代码(mybatis generator)

    pom.xml 文件配置 引入 mybatis generator <properties> <mysql.connector.version>5.1.44</mysql ...

  6. ButterKnife的使用以及不能自动生成代码问题的解决

    ButterKnife的使用以及不能自动生成代码问题的解决 转载请注明出处:http://www.cnblogs.com/zhengjunfei/p/5910497.html 最近换了个工作刚入职,又 ...

  7. 【MyBatis】MyBatis自动生成代码查询之爬坑记

    前言 项目使用SSM框架搭建Web后台服务,前台后使用restful api,后台使用MyBatisGenerator自动生成代码,在前台使用关键字进行查询时,遇到了一些很宝贵的坑,现记录如下.为展示 ...

  8. mybatis-generator : 自动生成代码

    [参考文章]:mybatis generator自动生成代码时 只生成了insert 而没有其他 [参考文章]:Mybatis Generator最完整配置详解 1. pom <plugin&g ...

  9. mybatis-generator自动生成代码插件

    mybatis自动生成代码(实体类.Dao接口等)是很成熟的了,就是使用mybatis-generator插件. 它是一个开源的插件,使用maven构建最好,可以很方便的执行 插件官方简介: http ...

随机推荐

  1. 修改JRE system library

    MyEclipse 默认的情况下JRE system library 是:MyEclipse 的,如何修改工程中的JRE system library呢?步骤如下: 1.选择工程->Proper ...

  2. Monkeyrunner介绍

    Monkeyrunner概述 Monkeyrunner是由Google开发.用于android系统的自动化测试工具,由android系统自带,存在于android sdk中(sdk:software ...

  3. codevs 2905 足球晋级

    时间限制: 1 s  空间限制: 64000 KB  题目等级 : 黄金 Gold   题目描述 Description A市举行了一场足球比赛 一共有4n支队伍参加,分成n个小组(每小组4支队伍)进 ...

  4. pickle 两个使用小方法

    def pickle_load(file_path): f = open(file_path,'r+') data = pickle.load(f) f.close() return data     ...

  5. exit - 使程序正常中止

    SYNOPSIS 总览 #include <stdlib.h> void exit(int status); DESCRIPTION 描述 函数 exit() 使得程序正常中止,statu ...

  6. BI结构图及自动建表结构图

  7. PHP24 自定义分页类

    分页类的定义 <?php /** * Class MyPage 分页类 * @package core */ class MyPage { private $totalCount; //数据表中 ...

  8. dpdk快速编译使用

    QuickStart 环境 dpdk: dpdk-17.11 运行前配置 配置系统HugePages #mkdir /mnt/huge_1GB/ #vim /etc/fstab nodev /mnt/ ...

  9. RestTemplate-postForObject源码

    参数:    请求路径, 请求参数, 返回类型, 扩展模板变量

  10. 7. 配置undo表空间

    7. 配置undo表空间 undo日志可以存储在一个或多个undo表空间中,无需存储在系统表空间中. 要为MySQL实例配置单独的undo表空间,请执行以下步骤 [重要]: 只能在初始化新MySQL实 ...