Search code examples
c#asp.nettemplatesitemplateloadcontrol

Can I load an ITemplate from a database or string?


I'm looking to implement some templates in a web application and wanted to utilize ASP.NET's templated controls. However, I don't want to rely on physical .ascx files, or the VirtualPathProvider in order to Load the templates.

I want to be able to load the templates from a database or other datastore (in memory?). Is there any implementation of a LoadTemplate() method that returns an ITemplate given a string representation of an .ascx template?

If not, how would I go about writing one?

FYI, Kentico has a similar feature, but they rely on the VirtualPathProvider in order to use the LoadTemplate() on the TemplateControl class. With that method, they are able to load templates (they call them transformations) stored in the database.


Solution

  • Yes, VirtualPathProvider is probably the method you will want to use, if a string or database is the source you want to use. (There are also code generators that can emit code, but usually those are used when building the code dynamically--not loading from an external source as in your case.)

    You don't mention why you don't want to use the VirtualPathProvider though. Is it due to not wanting to, or can't because of some special requirements you have in a particular situation?

    Finally, if it "seems trivial" to load and compile code dynamically, then you don't know what all the whole .Net system has to do before it can run dynamic code--assembly generation, compilation and JIT, application contexts, class/member name resolution, code security, etc. Maybe you've just been spoiled with how easy .Net has made doing other complicated tasks. ;-)