2011-07-07 22 views
4

最近、私はpostを読んでいます。ここでは、かみそりビューを別々のライブラリにコンパイルする方法について説明しています。コンパイルせずにライブラリにビューを埋め込むことは可能ですか?次に、カスタムVirtualPathProviderを追加してビューを読み取ります。あなたの「殻」MVCプロジェクトのGlobal.asaxののApplication_Startで埋め込みカミソリビュー

答えて

1

カスタムVirtualPathProviderを登録します。

HostingEnvironment.RegisterVirtualPathProvider(new CustomVirtualPathProvider()); 

あなたはおそらく、いくつかのインターフェイスベース、反射、データベース検索を行うだろうので、実際の実装は、これよりももっと複雑になります

public class CustomVirtualPathProvider : VirtualPathProvider { 
    public override bool DirectoryExists(string virtualDir) { 
     return base.DirectoryExists(virtualDir); 
    } 

    public override bool FileExists(string virtualPath) { 
     if (virtualPath == "/Views/Foo/Index.cshtml") { 
      return true; 
     } 
     else { 
      return base.FileExists(virtualPath); 
     } 
    } 

    public override System.Web.Caching.CacheDependency GetCacheDependency(string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart) { 
     if (virtualPath == "/Views/Foo/Index.cshtml") { 
      Assembly asm = Assembly.Load("AnotherMvcAssembly"); 
      return new CacheDependency(asm.Location); 
     } 
     else { 
      return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart); 
     } 
    } 

    public override string GetCacheKey(string virtualPath) { 
     return base.GetCacheKey(virtualPath); 
    } 

    public override VirtualDirectory GetDirectory(string virtualDir) { 
     return base.GetDirectory(virtualDir); 
    } 

    public override VirtualFile GetFile(string virtualPath) { 
     if (virtualPath == "/Views/Foo/Index.cshtml") { 
      return new CustomVirtualFile(virtualPath); 
     } 
     else { 
      return base.GetFile(virtualPath); 
     } 
    } 
} 

public class CustomVirtualFile : VirtualFile { 
    public CustomVirtualFile(string virtualPath) : base(virtualPath) { } 

    public override System.IO.Stream Open() { 
     Assembly asm = Assembly.Load("AnotherMvcAssembly"); 
     return asm.GetManifestResourceStream("AnotherMvcAssembly.Views.Foo.Index.cshtml"); 
    } 
} 
2
:などのメタデータを引っ張る手段として、これは一般的な考え(あなたはフー・コントローラとIndex.cshtmlビューで「AnotherMvcAssembly」という名前の別のMVCプロジェクトは、埋め込みリソースとしてマークされていると仮定するだろう

私のEmbeddedResourceVirtualPathProviderはNuget経由でインストールすることができます。参照されているアセンブリからリソースをロードし、開発中にソースファイルに依存するように設定して、再コンパイルを必要とせずにビューを更新することもできます。

+0

あなたのライブラリが私のために働いていました。ナゲットパッケージを作る努力をしてくれてありがとう。 –