通过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. js实现跨域的方法

    由于同源策略的限制,XMLHttpRequest只允许请求当前源(包含域名.协议.端口)的资源. json与jsonp的区别:    JSON是一种数据交换格式,而JSONP是一种依靠开发人员创造出的 ...

  2. ASP.NET Core 企业级开发架构简介及框架汇总 (转载)

    ASP.NET Core 企业开发架构概述 企业开发框架包括垂直方向架构和水平方向架构.垂直方向架构是指一个应用程序的由下到上叠加多层的架构,同时这样的程序又叫整体式程序.水平方向架构是指将大应用分成 ...

  3. C#创建任务计划

    因写的调用DiskPart程序是要用管理员身份运行的,这样每次开机检查都弹个框出来确认肯定不行.搜了下,似乎也只是使用任务计划程序运行来绕过UAC提升权限比较靠谱,网上的都是添加到计算机启动的,不是指 ...

  4. (转)SpringMVC学习(十二)——SpringMVC中的拦截器

    http://blog.csdn.net/yerenyuan_pku/article/details/72567761 SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter, ...

  5. (转)使用JDK中的Proxy技术实现AOP功能

    http://blog.csdn.net/yerenyuan_pku/article/details/52863780 AOP技术在企业开发中或多或少都会用到,但用的最多的大概就是做权限系统时,在做权 ...

  6. Java随机产生中文昵称

    有时候我们注册一个网站第一次登陆系统会产生一个随机昵称供用户选择,在项目测试阶段遇到了这个问题,因为注册时没有让用户填写昵称,于是找了两种产生随机中文昵称的方法: 代码如下 package com.u ...

  7. xorequation(DFS完全枚举)

    题目 有一个含有N个未知数的方程如下: x1^x2^...^xn= V,给定N,V,再给定正整数a1,a2,...an满足1≤ai≤9且∏Ni=1(ai+1)  ≤ 32768,请输出所有满足0≤xi ...

  8. jeecms

    ===标签=== <!-- 显示一级栏目对应的二级栏目 --> <!-- [@cms_channel_list parentId=c.id] [#if tag_list?size&g ...

  9. uva1612 Guess

    和cf的打分有点像啊 因为一共只有三道题,所以每个人的得分最多有8种可能性.把这8种可能性都算出来,存在数组里,排好序备用排名就是一个天然的链表,给出了扫描的顺序扫描时,维护两个变量:前一个playe ...

  10. C++ 给自己的扫盲笔记

    1.运算符new分配内存的格式: 指针变量名 = new 类型: 如分配一个20字节的name变量    :name = new char[20]; 2.strlen(s);函数: 返回字符串s的长度 ...