ViewEnginePartMethods.cs
2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace NCC.ViewEngine
{
/// <summary>
/// 字符串模板执行部件
/// </summary>
public sealed partial class ViewEnginePart
{
/// <summary>
/// 编译并运行
/// </summary>
public string RunCompile()
{
return InvokeRunCompileMethod(nameof(IViewEngine.RunCompile)) as string;
}
/// <summary>
/// 编译并运行
/// </summary>
public Task<string> RunCompileAsync()
{
return InvokeRunCompileMethod(nameof(IViewEngine.RunCompileAsync)) as Task<string>;
}
/// <summary>
/// 通过缓存解析模板
/// </summary>
public string RunCompileFromCached()
{
return InvokeRunCompileMethod(nameof(IViewEngine.RunCompileFromCached), true) as string;
}
/// <summary>
/// 通过缓存解析模板
/// </summary>
public Task<string> RunCompileFromCachedAsync()
{
return InvokeRunCompileMethod(nameof(IViewEngine.RunCompileFromCachedAsync), true) as Task<string>;
}
/// <summary>
/// 执行模板方法
/// </summary>
/// <param name="methodName"></param>
/// <param name="isCached"></param>
/// <returns></returns>
private object InvokeRunCompileMethod(string methodName, bool isCached = false)
{
var viewEngine = GetViewEngine();
var viewEngineType = viewEngine.GetType();
// 反射获取视图引擎方法
var runCompileMethod = TemplateModel.Type == typeof(object)
? viewEngineType.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.First(m => m.Name == methodName && !m.IsGenericMethod)
: viewEngineType.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.First(m => m.Name == methodName && m.IsGenericMethod)
.MakeGenericMethod(TemplateModel.Type);
return !isCached
? runCompileMethod.Invoke(viewEngine, new object[] {
Template,TemplateModel.Model,TemplateOptionsBuilder
})
: runCompileMethod.Invoke(viewEngine, new object[] {
Template,TemplateModel.Model,TemplateCachedFileName, TemplateOptionsBuilder
});
}
/// <summary>
/// 获取视图引擎对象
/// </summary>
/// <returns></returns>
private IViewEngine GetViewEngine()
{
return App.GetService<IViewEngine>(ViewEngineScoped ?? App.RootServices)
?? throw new InvalidOperationException("Please confirm whether the view engine is registered successfully.");
}
}
}