Questions tagged [postsharp]

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.

916 questions
5
votes
3 answers

AOP Pre-compile time weaving?

I have been playing along with AOP for years, but didnt become 100% satisfied with the solutions. AOP Frameworks with runtime weaving, like Spring.AOP, cannot change the interface of a class. With post compile time Frameworks like Postsharp…
Thomas Haller
  • 199
  • 1
  • 11
5
votes
1 answer

I am getting "Cannot serialized the aspects: Type 'log4net.Core.LogImpl' in assembly 'log4net...'" -how can I make it serializable?

Environment Windows 7 x64 PostSharp 2.1.7.30 installed PostSharp 2.1.7.29 (reference retrieved from the PostSharp install directory) log4net 1.2.11.0 (reference retrieved from the net\2.0\release directory of the log4net binaries download) ASP.NET…
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
5
votes
2 answers

Passing Func<> or similar to PostSharp aspect

In our external boundaries that expose WCF services, we convert all internal exceptions to FaultException. This is a manual process which often has minor flaws unique to each implementation. It has been copy/pasted and mindlessly modified (or…
carlpett
  • 12,203
  • 5
  • 48
  • 82
5
votes
1 answer

PostSharp and uninitialized objects

Assumed I have an aspect implementing IInstanceScopedAspect and I have this aspect applied to methods in a type. How can I initialize the aspects when creating the object with FormatterServices.GetUninitializedObject? The constructor is not executed…
Matthias
  • 15,919
  • 5
  • 39
  • 84
5
votes
1 answer

Best way of validating WCF and WebService method parameter values

I'm going to write a validation component to use it on different projects. I'm not really familiar with any of validation frameworks like Enterprise Library VAB, Fluent, CuttingEdge.Conditions and so many others, however I don't have time to work…
Ashkan
  • 3,322
  • 4
  • 36
  • 47
5
votes
4 answers

Which Tools Perform Post-Compile Modification of IL?

A recent mention of PostSharp reminded me of this: Last year where I worked, we were thinking of using PostSharp to inject instrumentation into our code. This was in a Team Foundation Server Team Build / Continuous Integration environment. Thinking…
John Saunders
  • 160,644
  • 26
  • 247
  • 397
5
votes
1 answer

PostSharp inserting k__Backing Field into Entity Class, causing Database generation to fail

I'm creating a Database using the Microsoft Entity Framework and CodeFirst in C#. I want to use the Database in a WPF-Application, so the Entity-Classes should implement "INotifyPropertyChanged". This can be done very elegantly using a PostSharp…
BoltzmannBrain
  • 219
  • 2
  • 13
5
votes
3 answers

AOP with MonoTouch

I was wondering if there is any support for AOP (Aspect Oriented Programming) together with MonoTouch (and thereby with MonoDevelop). So far I was not able to find any tools that support MonoDevelop. As far as I can see, tools like PostSharp are not…
4
votes
1 answer

How to set a default NHibernate CommandTimeOut default value

How can i set an Session.DBCommand.CommandTimeOut NHibernate default value with Castle ActiveRecord? this config line don't work. edit: i need some…
manuellt
  • 669
  • 2
  • 7
  • 19
4
votes
1 answer

postsharp exception is null

I have a probleme with Postsharp. i have this: [Serializable] public class MethodConnectionTracking: OnExceptionAspect { public override void OnException(MethodExecutionArgs args) { base.OnException(args); } } and…
Müsli
  • 1,744
  • 7
  • 27
  • 50
4
votes
2 answers

Is it possible to add methods to classes with PostSharp? If yes, is it possible to then reference those methods from other classes?

Let's say I have a class Abc: class Abc { } and that I'd like to externally add some method m() to it. I guess it's probably possible to do this, although I am not sure how. Assuming it is possible to do that, let's then say Abc does have, from now…
devoured elysium
  • 101,373
  • 131
  • 340
  • 557
4
votes
1 answer

How can I apply postsharp aspect to a website project?

I use a simple postsharp.config file :
Amon
  • 296
  • 1
  • 14
4
votes
1 answer

Alternative for MethodInterceptionAspect

I need to limit some function regarding license . so i created an attribute using MethodInterceptionAspect in postSharp and validate the fields i need. is there any other 3rd party making aop custom attributes ? i know dynamic proxy is exist but i…
Tal Cohen
  • 63
  • 5
4
votes
2 answers

PostSharp aspect resolving type

We are using dependency injection with and IoC (Unity) and now I want to make an aspect with PostSharp that would basically log enter/exit of a method. My problem is that my logger is configured and registered in the unity container. What should be…
Michael
  • 1,081
  • 1
  • 12
  • 27
4
votes
3 answers

Generating immutable value object in C#: PostSharp or T4 templates?

I'm getting sick of boilerplate immutable value object code. Would either PostSharp or T4 templates allow me to do the following transformation? Input: public struct Name { public string FirstName; public string LastName; } Output: public…
Domenic
  • 110,262
  • 41
  • 219
  • 271