Open sandboxFocusImprove this doc

Accessing Configuration from Source Code

Although PostSharp or its add-ins consume most configuration settings, it is sometimes useful to access configuration elements from user code. The PostSharp.dll library gives access to both configuration properties and extension configuration elements.

The configuration is available only at build time, when PostSharp processes the project. Therefore, use the CurrentProject property in build-time code, for instance in the CompileTimeInitialize method of an aspect.

Accessing properties

You can read the value of any PostSharp property by including it in an XPath expression and evaluating it using the EvaluateExpression(string) method of CurrentProject:

string value = PostSharpEnvironment.CurrentProject.EvaluateExpression( "{$Greeting}" );

For details regarding expressions, see Using Expressions in Configuration Files.

Accessing custom sections

You can get a list of custom sections of a given name and namespace by calling the GetExtensionElements(string, string) method of CurrentProject:

IEnumerable<ProjectExtensionElement> elements =
PostSharpEnvironment.CurrentProject.GetExtensionElements( "MyElement", "uri:MyNamespace" );

Extension elements must be declared using the SectionType element.

For instance, the following postsharp.config file defines the Greeting property and two MyElement sections:

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.postsharp.org/1.0/configuration">
  <Property Name="Greeting" Value="Hello from postsharp.config" />
  <SectionType LocalName="MyElement" Namespace="uri:MyNamespace" />
  <MyElement xmlns="uri:MyNamespace" Name="first" />
  <MyElement xmlns="uri:MyNamespace" Name="second" />
</Project>

An aspect that reads them in CompileTimeInitialize and writes them at run time produces the following output:

Greeting: Hello from postsharp.config
Elements: first, second

See Also

Other Resources

Using Expressions in Configuration Files
Configuring Projects Using postsharp.config