Exemplo n.º 1
0
        public static async Task <string> RunAsync <TTemplate, TModel>(
            this IRazorEngineCompiledTemplate <TTemplate> compiledTemplate,
            TModel model = default)
            where TModel : class
            where TTemplate : class, IRazorEngineTemplate
        {
            if (compiledTemplate == null)
            {
                throw new ArgumentNullException(nameof(compiledTemplate));
            }

            if (model?.IsAnonymous() == true)
            {
                return(await compiledTemplate.RunAsync(model : (object)model));
            }

            var templateType = compiledTemplate.GetReflectedTemplateType();

            IRazorEngineTemplate instance = (IRazorEngineTemplate)Activator.CreateInstance(templateType);

            // Find the correct property to update via reflection.
            // As IRazorEngineTemplateBase<T> inherits from IRazorEngineTemplateBase and the both have `Model`
            var propertyInfo = instance.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty)
                               .FirstOrDefault(fd => fd.Name.Equals(nameof(IRazorEngineTemplate.Model)) && fd.PropertyType == typeof(TModel));

            if (propertyInfo != null)
            {
                propertyInfo.SetValue(instance, model);
            }
            else
            {
                instance.Model = model;
            }

            await instance.ExecuteAsync();

            return(instance.Result());
        }