RazorEngine將模板cshtml編譯成了。一個程序集,每次編譯運行,都會產生一個程序集;
可以用一個控制檯程序打印出來,生成的“動態程序集“的名字(動態程序集是不能打印出磁盤中的位置的)
using RazorEngine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Razor解密
{
class Program
{
static void Main(string[] args)
{
string cshtml = File.ReadAllText(@"C:\Users\Administrator\Desktop\ceshi\Web2\Web2\Razor.cshtml");
for (int i = 0; i < 5; i++)
{
string html = Razor.Parse(cshtml);//將一個模板頁轉化爲一個程序集
// Console.WriteLine(html);
}
//找到本程序中所有引用的程序集
Assembly[] asd = AppDomain.CurrentDomain.GetAssemblies(); //Assembly 添加using
foreach(Assembly a in asd)
{
Console.WriteLine(a.FullName+"\r\n");
}
Console.ReadKey();
}
}
}
生成的程序集如下;
產生的問題:
可以看到生成的程序集非常的多,模板每一次,有新的變量添加(頁面內容的添加,就會重複編譯,動態生成多個的程序集),大量程序集的影響網站的打開速度的性能
解決辦法:給模板頁取個別名”緩存名字“
using RazorEngine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Razor解密
{
class Program
{
static void Main(string[] args)
{
/*
string cshtml = File.ReadAllText(@"C:\Users\Administrator\Desktop\ceshi\Web2\Web2\Razor.cshtml");
*/
/*
for (int i = 0; i < 5; i++)
{
//給要解析模板文件cshtml一個別名字"緩存名",c1
//這次一旦編成功後,下次如果是再次編譯這個相同的模板文件cshtml的話,就讓RazorEngine引擎來轉換c1好了
string html = Razor.Parse(cshtml, null, "c1");
//爲了好理解,可以給這個cshtml相同的模板文件再起個別的緩存名字"c2"
//
}
*/
/*
string html = Razor.Parse(cshtml, null, "c1");
Razor.Parse(cshtml, null, "c2");
*/
//1.取得文件的路徑
string fullPath=File.ReadAllText(@"C:\Users\Administrator\Desktop\ceshi\Web2\Web2\Razor.cshtml");
for (int i = 0; i < 10; i++)
{
//2.讀出模板中的內容
string cshtml = File.ReadAllText(fullPath);
//取文件的全路徑+文件修改的時間做cacheName不一樣(每一次文件的編譯的時候用的都是同一個緩存的名字)
//修改時間保證相同文件做了內容修改之後的cacheName不一樣(也可以用文件內容的MD5值,)
string cacheName = fullPath + File.GetLastWriteTime(fullPath);
string html = Razor.Parse(cshtml, null, cacheName);
Console.WriteLine(html);
}
//找到本程序中所有引用的程序集
Assembly[] asd = AppDomain.CurrentDomain.GetAssemblies(); //Assembly 添加using
foreach(Assembly a in asd)
{
Console.WriteLine(a.FullName+"\r\n");
}
Console.ReadKey();
}
}
}
取了一個別名字後動態程序集生成的效果
發現只有一個了
給同一個模板頁取兩個不同的別名字後效果
給同一個模板頁取加上時間的別名字後效果