using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace NCC.ViewEngine
{
///
/// 字符串模板执行部件
///
public sealed partial class ViewEnginePart
{
///
/// 编译并运行
///
public string RunCompile()
{
return InvokeRunCompileMethod(nameof(IViewEngine.RunCompile)) as string;
}
///
/// 编译并运行
///
public Task RunCompileAsync()
{
return InvokeRunCompileMethod(nameof(IViewEngine.RunCompileAsync)) as Task;
}
///
/// 通过缓存解析模板
///
public string RunCompileFromCached()
{
return InvokeRunCompileMethod(nameof(IViewEngine.RunCompileFromCached), true) as string;
}
///
/// 通过缓存解析模板
///
public Task RunCompileFromCachedAsync()
{
return InvokeRunCompileMethod(nameof(IViewEngine.RunCompileFromCachedAsync), true) as Task;
}
///
/// 执行模板方法
///
///
///
///
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
});
}
///
/// 获取视图引擎对象
///
///
private IViewEngine GetViewEngine()
{
return App.GetService(ViewEngineScoped ?? App.RootServices)
?? throw new InvalidOperationException("Please confirm whether the view engine is registered successfully.");
}
}
}