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
7
votes
1 answer

Simplest way to mock properties of PostSharp attribute

I'm using a PostSharp method attribute to do authorisation and auditing on my WCF service. It's working properly but now I'm trying to get my unit tests working with the attribute and am struggling to find a way to mock and inject the properties on…
sipsorcery
  • 30,273
  • 24
  • 104
  • 155
7
votes
1 answer

How to inject an attribute using a PostSharp attribute?

How can I write a PostSharp aspect to apply an attribute to a class? The scenario I'm considering is a WCF entity (or domain object) that needs to be decorated with the DataContract attribute. It should also have a Namespace property. Like…
Paul Fryer
  • 9,268
  • 14
  • 61
  • 93
7
votes
3 answers

Can you apply aspects in PostSharp without using attributes?

I know with Castle Windsor, you can register aspects (when using method interception in Windsor as AOP) using code instead of applying attributes to classes. Is the same possible in Postsharp? It's a preference things, but prefer to have aspects…
Bless Yahu
  • 1,331
  • 1
  • 12
  • 25
7
votes
2 answers

How can I implement a UpdateCallback on a CacheItemPolicy from another class?

I have a simple Cache attribute implemented using postsharp. When I set the cache policy I want to be able to set a update callback like below. private static CacheItemPolicy GetCachePolicy(CacheType type, int expiry) { var policy =…
Lee Cook
  • 573
  • 4
  • 18
7
votes
2 answers

Multiple aspects on one method

In my application I previously used regular C# attributes to "annotate" a method. E.g.: [Foo(SomeKey="A", SomeValue="3")] [Foo(SomeKey="B", SomeValue="4")] public void TheMethod() { SpecialAttributeLogicHere(); } What…
7
votes
2 answers

Triggering "CanExecute" on postsharp [Command] when a document changes?

I am currently migrating a project to PostSharp to remove a lot of boilerplate code, most of it is going very smoothly but I'm left confused about how to force a command to recheck if it CanExecute. I expected PostSharp would inspect the command…
Ronan Thibaudau
  • 3,413
  • 3
  • 29
  • 78
7
votes
2 answers

C# 7 Local Functions: are attributes / aspects allowed?

C# 7 introduced local functions (which is great!). Suppose I have the following code: using System; using PostSharp.Aspects; namespace AspectCS7 { class Program { private static void Main() …
user2341923
  • 4,537
  • 6
  • 30
  • 44
7
votes
1 answer

PostSharp on assemblies I don't have source for

In the examples on their website, PostSharp has a demo of intercepting calls in main system assemblies. I have tried a few times to setup and replicate said intercept calls on assemblies I don't have the source code for with no success. My approach…
pinvoke
  • 331
  • 1
  • 3
  • 10
7
votes
1 answer

AssemblyLoadException in postsharp, problem with arguments from referenced DLLs?

I'm just starting out with postsharp/AOP. I want to make some instrumentation for C# to track the usage of some addins that I write for a peice of software. I am trying to use the OnMethodBoundaryAspect class to take note of the values of some of…
RodH257
  • 3,552
  • 5
  • 36
  • 46
7
votes
1 answer

Remove PostSharp reference after build?

Is is possible to get postsharp to remove references to the postsharp assemblies during a build? I have an exe i needs to have a very small footprint. I want to use some of the compile time weaving of postsharp but dont want to have to deploy…
Simon
  • 33,714
  • 21
  • 133
  • 202
7
votes
5 answers

NuGet restoring PostSharp package before the build begins

I am using PostSharp and I have the following target description in my project file:
Dave New
  • 38,496
  • 59
  • 215
  • 394
7
votes
1 answer

Any experience of using PostSharp with ReSharper

Has anyone used PostSharp with ReSharper, if so what problems should I expect?
Ian Ringrose
  • 51,220
  • 55
  • 213
  • 317
6
votes
2 answers

How to write attribute that catches exceptions and removes stacktrace?

I wish to write an attribute for a function (or class) that will catch any exception thrown and set its StackTrace property to string.Empty. How can I do this? EDIT: If I cannot accomplish this in plain C#, how can I do this in C# with PostSharp?
cm007
  • 1,352
  • 4
  • 20
  • 40
6
votes
4 answers

C# Possible to attach an Object to a method call without having it as a parameter?

I am designing a program with AOP architecture(postsharp) that will intercept all method calls but I need a way to attach a class to every call. The problem is I don't want to have to pass the class explicitly in every single method call. So is…
Terrance Jackson
  • 606
  • 3
  • 13
  • 40
6
votes
0 answers

How to introduce new property based on existing property and modify existing one?

I am trying to automate this XmlSerializer workaround pattern. See update below. Is it possible to introduce new property based on existing property and modify attributes of existing one using PostSharp (or maybe some other AOP tool) ? It would be…
Anton Krouglov
  • 3,077
  • 2
  • 29
  • 50
1 2
3
61 62