PostSharp is a pattern-aware extension to C# and VB, reducing boilerplate code involved in implementing design patterns. It is based on aspect-oriented programming and static analysis.
With PostSharp, you can easily write and apply custom attributes that add new behaviors to your code - tracing, thread management, exception handling, data binding, and much more.
PostSharp works by injecting IL during the build process to weave aspects into the original method.
Ready-made patterns
PostSharp comes with a library of ready-made pattern implementations including code contracts, INotifyPropertyChanged, immutable, freezable and other threading models.
Example: the following snippet shows how the NotifyPropertyChanged attribute automatically implementes the INotifyPropertyChanged interface, including listening to two levels of child objects.
[NotifyPropertyChanged]
public class CustomerViewModel
{
public CustomerModel Customer { get; set; }
public string FullName
{
get
{
if (Customer == null) return null;
return string.Format("{0} {1} from {2}",
Customer.FirstName,
Customer.LastName,
Customer.PrincipalAddress != null ?
Customer.PrincipalAddress.FullAddress : "?");
}
}
}
Custom patterns
PostSharp also has a rich toolkit to automate the implementation of your own patterns.
Examples:
Tracing:
[PSerializable]
public class TraceAttribute : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
Trace.TraceInformation("Entering {0}.", eventArgs.Method);
}
public override void OnExit(MethodExecutionEventArgs eventArgs)
{
Trace.TraceInformation("Leaving {0}.", eventArgs.Method); }
}
}
Thread dispatch WPF:
[PSerializable]
public class GuiThreadAttribute : OnMethodInvocationAspect
{
public override void OnInvocation(MethodInvocationEventArgs eventArgs)
{
DispatcherObject dispatcherObject = (DispatcherObject)eventArgs.Delegate.Target;
if (dispatcherObject.CheckAccess())
eventArgs.Proceed();
else
dispatcherObject.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(() => eventArgs.Proceed()));
}
}
Usage:
[Trace]
public void CreateCustomer(int id, string name) { /* ... */ }
Installation
PostSharp can most easily be installed through its NuGet package.
Install-Package PostSharp
Licensing
PostSharp is a commercial product with a free edition.