Регистрация пользовательского ASP.NET ExpressionBuilder программно - PullRequest
0 голосов
/ 05 октября 2018

Можно ли программно зарегистрировать пользовательский класс ExpressionBuilder во время запуска приложения?

Эквивалентное объявление web.config очевидно:

  <system.web>
    <compilation>
      <expressionBuilders>
        <add expressionPrefix="MyPrefix" type="MyNamespace.MyExpressionBuilder">
      </expressionBuilders>
    </compilation>
  </system.web>

Как мне зарегистрировать это динамически либово время пользовательского HTTP-модуля Init(), запуска приложения или BeginRequest без изменения web.config?

1 Ответ

0 голосов
/ 08 октября 2018

Я нашел ExpressionBuilderCollection Class

, который включал следующий пример

class UsingExpressionBuildCollection {
    static void Main(string[] args)
    {
      try
      {
        // Set the path of the config file.
        string configPath = "";

        // Get the Web application configuration object.
        Configuration config =
          WebConfigurationManager.OpenWebConfiguration(configPath);

        // Get the section related object.
        CompilationSection configSection =
          (CompilationSection)config.GetSection("system.web/compilation");

        // Display title and info.
        Console.WriteLine("ASP.NET Configuration Info");
        Console.WriteLine();

        // Display Config details.
        Console.WriteLine("File Path: {0}",
          config.FilePath);
        Console.WriteLine("Section Path: {0}",
          configSection.SectionInformation.Name);

        // Create a new ExpressionBuilder reference.
        ExpressionBuilder myExpressionBuilder =
          new ExpressionBuilder("myCustomExpression", "MyCustomExpressionBuilder");
        // Add an ExpressionBuilder to the configuration.
        configSection.ExpressionBuilders.Add(myExpressionBuilder);

        // Add an ExpressionBuilder to the configuration.
        ExpressionBuilder myExpressionBuilder2 =
          new ExpressionBuilder("myCustomExpression2", "MyCustomExpressionBuilder2");
        configSection.ExpressionBuilders.Add(myExpressionBuilder2);

        // Display the ExpressionBuilder count.
        Console.WriteLine("ExpressionBuilder Count: {0}",
          configSection.ExpressionBuilders.Count);

        // Display the ExpressionBuildersCollection details.
        int i = 1;
        int j = 1;
        foreach (ExpressionBuilder expressionBuilder in configSection.ExpressionBuilders)
        {
          Console.WriteLine();
          Console.WriteLine("ExpressionBuilder {0} Details:", i);
          Console.WriteLine("Type: {0}", expressionBuilder.ElementInformation.Type);
          Console.WriteLine("Source: {0}", expressionBuilder.ElementInformation.Source);
          Console.WriteLine("LineNumber: {0}", expressionBuilder.ElementInformation.LineNumber);
          Console.WriteLine("Properties Count: {0}", expressionBuilder.ElementInformation.Properties.Count);
          j = 1;
          foreach (PropertyInformation propertyItem in expressionBuilder.ElementInformation.Properties)
          {
            Console.WriteLine("Property {0} Name: {1}", j, propertyItem.Name);
            Console.WriteLine("Property {0} Value: {1}", j, propertyItem.Value);
            ++j;
          }
          ++i;
        }

        // Remove an ExpressionBuilder.
        configSection.ExpressionBuilders.RemoveAt
          (configSection.ExpressionBuilders.Count-1);

        // Remove an ExpressionBuilder.
        configSection.ExpressionBuilders.Remove("myCustomExpression");

        // Update if not locked.
        if (!configSection.SectionInformation.IsLocked)
        {
          config.Save();
          Console.WriteLine("** Configuration updated.");
        }
        else
        {
          Console.WriteLine("** Could not update, section is locked.");
        }
      }

      catch (Exception e)
      {
        // Unknown error.
        Console.WriteLine(e.ToString());
      }

      // Display and wait.
      Console.ReadLine();
    }
  }
}

Важной частью является

Configuration config =
      WebConfigurationManager.OpenWebConfiguration(configPath);

// Get the section related object.
CompilationSection configSection =
  (CompilationSection)config.GetSection("system.web/compilation");

//...

// Create a new ExpressionBuilder reference.
var myExpressionBuilder = new ExpressionBuilder(
    expressionPrefix: "MyPrefix", 
    theType: "MyNamespace.MyExpressionBuilder"
);
// Add an ExpressionBuilder to the configuration.
configSection.ExpressionBuilders.Add(myExpressionBuilder);

//...

// Update if not locked.
if (!configSection.SectionInformation.IsLocked) {
  config.Save();
}

Выше было быбыть эквивалентным этому образцу конфигурации.

  <system.web>
    <compilation>
      <expressionBuilders>
        <add expressionPrefix="MyPrefix" type="MyNamespace.MyExpressionBuilder">
      </expressionBuilders>
    </compilation>
  </system.web>

Это открывает возможность сначала найти свой пользовательский компоновщик и добавить его при необходимости, проверить версии ... и т. д.

Обновить адресациюоб изменении файла конфигурации

После просмотра эталонного источника .net похоже, что анализатор страниц загружает конструкторы выражений непосредственно из конфигурации через внутренний ExpressionBuilder.GetExpressionBuilder .

Мне не удалось найти какие-либо другие точки расширения, отличные от тех, которые были показаны до сих пор, когда можно было бы программно внедрять пользовательские компоновщики.

Также, учитывая закрытую исходную природу System.Web Я сомневаюсь, что он будет в будущем.

...