ASP.NET Tutorial/Development/BuildProvider

Материал из .Net Framework эксперт
Версия от 11:56, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

BuildProvider must be compiled into a different assembly than the other code in the App_Code folder

You must add a BuildProvider to a separate subfolder because a BuildProvider must be compiled into a different assembly than the other code in the App_Code folder. 
Define the CustomBuildProviders folder and registers the SimpleBuildProvider.
Whenever you add a file with the .simple extension to the App_Code folder, the SimpleBuildProvider automatically compiles a new class based on the file.
File: Web.Config
<configuration>
    <system.web>
      <compilation>
        <codeSubDirectories>
          <add directoryName="CustomBuildProviders"/>
        </codeSubDirectories>
        <buildProviders>
          <add extension=".simple" type="MyNamespace.SimpleBuildProvider" />
        </buildProviders>
       </compilation>
    </system.web>
</configuration>


Creating a Custom BuildProvider

ASP.NET page gets compiled dynamically into a .NET class in the background by a BuildProvider.
Whenever you create a file that has the extension .simple, the SimpleBuilderProvider builds a new class with the same name as the file in the background. 
File: App_Code\SimpleBuildProvider.cs
using System;
using System.Web.rupilation;
using System.CodeDom;
using System.IO;
namespace MyNamespace
{
    public class SimpleBuildProvider : BuildProvider
    {
        public override void GenerateCode(AssemblyBuilder ab)
        {
            string fileName = Path.GetFileNameWithoutExtension(this.VirtualPath);
            string snippet = "public class " + fileName + @"{
                    public static void DoSomething(){}
                }";
            ab.AddCodeCompileUnit(this, new CodeSnippetCompileUnit(snippet));
        }
    }
}