Antaris / RazorEngine

Open source templating engine based on Microsoft's Razor parsing engine
http://antaris.github.io/RazorEngine
Other
2.14k stars 577 forks source link

Object type cannot be converted to target type #455

Open JimLixin opened 7 years ago

JimLixin commented 7 years ago

I received below error when deploy my application, not sure why this happen:

System.ArgumentException: Object type cannot be converted to target type.
   at RazorEngine.Compilation.CrossAppDomainCleanUp.CleanupHelper.Init(AppDomain domain, IPrinter printer)
   at RazorEngine.Compilation.CrossAppDomainCleanUp.InitHelper.CreateHelper()
   at RazorEngine.Compilation.ExecutionContextLessThread.CallHelperSafeHelper`2.AsAction()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at RazorEngine.Compilation.ExecutionContextLessThread.DefaultCallFunc[O](Func`1 f)
   at RazorEngine.Compilation.CrossAppDomainCleanUp..ctor(AppDomain toWatch, IPrinter printer)
   at RazorEngine.Compilation.CrossAppDomainCleanUp.CreateInitial()
   at System.Lazy`1.CreateValue()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Lazy`1.get_Value()
   at RazorEngine.Compilation.CrossAppDomainCleanUp.RegisterCleanup(String item, Boolean throwOnDefault)
   at RazorEngine.Templating.InvalidatingCachingProvider.CacheTemplate(ICompiledTemplate template, ITemplateKey templateKey)
   at RazorEngine.Templating.RazorEngineService.CompileAndCacheInternal(ITemplateKey key, Type modelType)
   at RazorEngine.Templating.TemplateService.CreateTemplate(String razorTemplate, Type staticType, Object model)
   at RazorEngine.Templating.TemplateService.Parse(String razorTemplate, Object model, DynamicViewBag viewBag, String cacheName)
matthid commented 7 years ago

It would be nice if you could reproduce this with a test or in the debugger and send me or better even post the test.

majorimi commented 7 years ago

I think this issue is duplicated. Are you trying to use it from ASP.NET? See this issue: https://github.com/Antaris/RazorEngine/issues/224

huchim commented 5 years ago

I have the same problem:

System.ArgumentException: Object type cannot be converted to target type.
   at RazorEngine.Compilation.CrossAppDomainCleanUp.CleanupHelper.Init(AppDomain domain, IPrinter printer)
   at RazorEngine.Compilation.CrossAppDomainCleanUp.InitHelper.CreateHelper()
   at RazorEngine.Compilation.ExecutionContextLessThread.FuncConv`1.Call(Boolean data)
   at RazorEngine.Compilation.ExecutionContextLessThread.CallHelperSafeHelper`2.AsAction()
   at RazorEngine.Compilation.ExecutionContextLessThread.CallHelperSafeHelper`2.AsContextCallback(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at RazorEngine.Compilation.ExecutionContextLessThread.DefaultCallFunc[O](Func`1 f)
   at RazorEngine.Compilation.CrossAppDomainCleanUp..ctor(AppDomain toWatch, IPrinter printer)
   at RazorEngine.Compilation.CrossAppDomainCleanUp.CreateInitial()
   at System.Lazy`1.CreateValue()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Lazy`1.get_Value()
   at RazorEngine.Compilation.CrossAppDomainCleanUp.get_CurrentCleanup()
   at RazorEngine.Compilation.CrossAppDomainCleanUp.RegisterCleanup(String item, Boolean throwOnDefault)
   at RazorEngine.Templating.InvalidatingCachingProvider.<>c.<.ctor>b__5_0(String item)
   at RazorEngine.Templating.InvalidatingCachingProvider.CacheTemplate(ICompiledTemplate template, ITemplateKey templateKey)
   at RazorEngine.Templating.DefaultCachingProvider.CacheTemplate(ICompiledTemplate template, ITemplateKey templateKey)
   at RazorEngine.Templating.RazorEngineService.CompileAndCacheInternal(ITemplateKey key, Type modelType)
   at RazorEngine.Templating.RazorEngineService.GetCompiledTemplate(ITemplateKey key, Type modelType, Boolean compileOnCacheMiss)
   at RazorEngine.Templating.RazorEngineService.RunCompile(ITemplateKey key, TextWriter writer, Type modelType, Object model, DynamicViewBag viewBag)
   at RazorEngine.Templating.DynamicWrapperService.RunCompile(ITemplateKey key, TextWriter writer, Type modelType, Object model, DynamicViewBag viewBag)
   at RazorEngine.Templating.RazorEngineServiceExtensions.<>c__DisplayClass16_0.<RunCompile>b__0(TextWriter writer)
   at RazorEngine.Templating.RazorEngineServiceExtensions.WithWriter(Action`1 withWriter)
   at RazorEngine.Templating.RazorEngineServiceExtensions.RunCompile(IRazorEngineService service, String name, Type modelType, Object model, DynamicViewBag viewBag)
   at BodaLink.Portal.Core.EmailService.GetEmailTemplate(String templateName, Object model)

And I can't reproduce it 😢

ASP NET: 4.0 IIS 8 RazorEngine: 3.9.0

public string GetEmailTemplate(string templateName, object model)
{
    var customEmailDirectory = (AppSettings.ViewsDirectory + "/Email/").Replace("//", "/");

    var templatePath = HttpContext.Current.Server.MapPath(Path.Combine(customEmailDirectory, templateName + ".cshtml"));
    var templateKey = templatePath.Replace("/", "-").Replace(":", "-").Replace(" ", "-");

    // First time is false, next time is true, next time is true until for some reason
    // return to false, and RunCompile thows that exception... :/
    var templateCached = Engine.Razor.IsTemplateCached(templateKey, model.GetType());

    string templateContent = string.Empty;

    try
    {
        templateContent = templateCached ?
            Engine.Razor.Run(templateKey, model.GetType(), model, null) :
            Engine.Razor.RunCompile(File.ReadAllText(templatePath), templateKey, model.GetType(), model, null);
    }
    catch (Exception ex)
    {
        Log.Error("---.", ex);
    }

    return templateContent;
}

When GetEmailTemplate fails I restart the application, and works fine again.

I will try with DisableTempFileLocking and I will return later jejeje

Is possible that var subscribeHelper = (SubscribeHelper)handle.Unwrap() is throwing that exception? I know you are creating an instance of typeof(SubscribeHelper)....

huchim commented 5 years ago

This solves my problem:

var config = new RazorEngine.Configuration.TemplateServiceConfiguration
{
        // This line doesn't work.
    DisableTempFileLocking = true,
    CachingProvider = new RazorEngine.Templating.DefaultCachingProvider(
                // log4net
        cacheFolder => Log.DebugFormat("Cache for {0} will be ignored", cacheFolder)
    ),
};

RazorEngine.Engine.Razor = RazorEngine.Templating.RazorEngineService.Create(config);
MarcelChirtes commented 5 years ago

Updated lately some projects in a solution in from 4.5 and 4.5.1 to 4.6, the problem appeared. The thing is that web project works, I have problems with tests, so yes the fix should do it as long I don't care about reaming files on disk by doing:

var config = new RazorEngine.Configuration.TemplateServiceConfiguration
                {
                    CachingProvider = new DefaultCachingProvider(t => { })
                };
Engine.Razor = RazorEngineService.Create(config);

Problem explained in depth here: https://github.com/Antaris/RazorEngine/issues/267