Search code examples
asp.net-mvcvirtualpathprovider

Reference problems when using VirtualPathProvider to dynamically load a view


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.


Solution

  • Try adding

    <%@ Import Namespace="MyApp.Model" %>
    

    to your dynamic user control string.

    EDIT:

    Of course, you could also use the fully qualified name for the type, changing Model.Category() to MyApp.Model.Category(). Most of the time, I import the namespace. Just a style preference.