I have the following set of classes that I used to dynamically load in a View. The code below works well when called with .RenderPartial.
public class VirtFile:VirtualFile
{
public VirtFile(string virtualPath) : base(virtualPath)
{
}
public override Stream Open()
{
string path = this.VirtualPath;
Stream str = new MemoryStream();
StreamWriter writer = new StreamWriter(str);
writer.Write(@"<%@ Control Language=""C#"" Inherits=""System.Web.Mvc.ViewUserControl"" %>
<%="Test"%>
");
writer.Flush();
str.Position = 0;
return str;
}
}
public class Provider:VirtualPathProvider
{
public override System.Web.Caching.CacheDependency GetCacheDependency(string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)
{
return null;
var dependency = new System.Web.Caching.CacheDependency(virtualPath);
return dependency;// base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
}
public override bool DirectoryExists(string virtualDir)
{
if (IsVirtual(virtualDir))
{
return true;
}
return base.DirectoryExists(virtualDir);
}
public override bool FileExists(string virtualPath)
{
if (IsVirtual(virtualPath))
{
return true;
}
return base.FileExists(virtualPath);
}
public override VirtualFile GetFile(string virtualPath)
{
if(IsVirtual(virtualPath))
{
return new VirtFile(virtualPath);
}
return base.GetFile(virtualPath);
}
private bool IsVirtual(string virtualPath)
{
return virtualPath.Contains("Database");
}
But if I try to change the <%="Test"%> to <%=new Model.Category()%>, of create a typed View I get an error stating that "The type or namespace name 'Model' could not be found (are you missing a using directive or an assembly reference?)". However, the same code works if it is simply placed in an .ascx file.
Am I missing something, it seems like wether the stream comes from the file system or a custom VirtualPathProvider it should have the same loaded assemblies, since <%=AppDomain.CurrentDomain.ApplicationIdentity%> returns the same value from either the file system or the custom provider.