adoconnection / RazorEngineCore

.NET6 Razor Template Engine
MIT License
583 stars 88 forks source link

DTO changes breaking the template rendering #106

Closed leodip closed 2 years ago

leodip commented 2 years ago

Hi,

Thanks for writing this library. It packs useful code for rendering razor templates.

I have a question. In my software I compile the template and save the bytes in the database.

To compile and render the template, I use a model that is a Dto.

Like this:

var compiledTemplate = await _razorEngine.CompileAsync<RazorEngineTemplateBase<MyDto>>(template.TemplateBody, builder =>
            {
                builder.AddAssemblyReference(typeof(MyDto));
                builder.AddAssemblyReferenceByName("System.Collections");
            });

Then:

var myDto= new MyDto()
            {
// ...
            };

            IRazorEngine razorEngine = new RazorEngine();

            MemoryStream memoryStream = new MemoryStream(compiledTemplate);
            IRazorEngineCompiledTemplate<RazorEngineTemplateBase<MyDto>> template = 
                RazorEngineCompiledTemplate<RazorEngineTemplateBase<MyDto>>.LoadFromStream(memoryStream);

            string html = await template.RunAsync(instance =>
            {
                instance.Model = myDto;
            });

The challenge I'm facing is: when we have changes in the DTO, the changes break the template rendering. For example, if I change a property type in the DTO from nullable to non-nullable, or change the property type from string to DateTime, etc. I get errors when the compiled template still references the previous version of the DTO.

I know the errors are natural and expected. I'm just wondering what can be done to better manage this...

So when you have a compiled template in the DB, and the DTO for that template changes, what can be done to prevent errors?

Thanks

adoconnection commented 2 years ago

Hi, thanks!

Compiled template is a regular assembly. Its like asking UI app to keep working after you changed the Model assembly. The most minimal change I see is to clean up DB compilted templates when you deploy app updates.

leodip commented 2 years ago

Yes, that makes sense. I need to come up with a strategy for that. It's like managing DB migrations. Code and DB schema need to be in sync when deploying. The same for the compiled template and model... Ok, thanks!