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

Logging with context information

I am working on a greenfield project and I want to integrate serilog with ninject. The use case is as follows: There are a number of common libraries These libraries are used in a number of modules i.e plugins. These plugins each receive a GUID at…
Bernard
  • 995
  • 2
  • 9
  • 20
3
votes
1 answer

can you inject dependencies into postsharp attribute using structure map

I use structure map for dependencies injection, I also now want to use postsharp for some authorisation checking at my service layer. because my service layer has all injected repositories is there a way I can inject or pass these repositories to…
monkeylee
  • 965
  • 3
  • 15
  • 32
3
votes
2 answers

PostSharp cannot use anonymous types with > 127 properties

Issue has been fixed in PostSharp 4.3.27 Given the following code in C# var obj = new { p0 = 0, p1 = 1 p2 = 2, // and so on until 127 ... p127 = 127 } I get this error trying to build the project with PostSharp…
John Merchant
  • 215
  • 1
  • 3
  • 10
3
votes
2 answers

How can I configure ReSharper to accept [Required] (from PostSharp) as equivalent to [NotNull] (or vice versa)?

I'm using PostSharp and ReSharper together in a variety of projects, specifically, making use of both PostSharp's code contract enforcement, and of ReSharper's annotations in the interest of better code. Trouble is, when it comes to nullability, I…
Cerebrate
  • 1,391
  • 11
  • 26
3
votes
1 answer

Accessing a request header from inside a custom PostSharp attribute

I'm trying to access a HttpRequestMessage from inside a custom PostSharp attribute. In my Web API I could do it like this: string headerText = Request.Headers.GetValues("TestHeader").First(); This doesn't seem to work outside of the API…
Nic
  • 12,220
  • 20
  • 77
  • 105
3
votes
1 answer

Unique logger inside Post Sharp attribute used by multiple threads

I have implemented Postsharp attribute as shown below and following are the usage details: Either have static Func GetLogger or static ThreadLocal TestLogger, which are set-up from the method HelloTask from Main program Aim is to have a…
Mrinal Kamboj
  • 11,300
  • 5
  • 40
  • 74
3
votes
1 answer

.NET CLI (dotnet build) and AOP libraries

Is it possible to get any AOP libraries running with the new .NET CLI; i.e. dotnet build? Most notably, I am looking for ways to do method interception. I am NOT looking for .NET Core compatibility. I am still using the normal .NET Framework.
Dave New
  • 38,496
  • 59
  • 215
  • 394
3
votes
1 answer

Custom IL Rewriting plugin for msbuild

I want to create a custom msbuild task that applies IL rwriting to my output assembly. At the moment i am already using PostSharp and now try to extend the rewriting capabilities. For some special cases i use Mono.Cecil to rewrite some proxy types…
3
votes
1 answer

Confirm that the declaration is correct?

i am using postsharp in my project. when i am trying to build the solution i am getting following error . "The "PostSharp.MSBuild.PostSharp30DetectNativeFrameworkVersion" task could not be loaded from the assembly…
user3883423
  • 247
  • 5
  • 19
3
votes
2 answers

PostSharp OutOfMemoryException during Visual Studio build

I'm using the latest version of PostSharp (version 4.1.31.0) in a C# solution with Visual Studio 2015 (with update 1). Everytime I try to build the solution I get the following error: Unhandled exception (4.1.31.0, postsharp.srv.4.0-x86.exe, CLR…
Ben Thomson
  • 1,083
  • 13
  • 29
3
votes
2 answers

Can you restrict the scope of an Extension Method to classes with a specific attribute?

We have a custom FileExtensionAttribute which we decorate our model classes which are based on file persistence with. It is defined as follows: [AttributeUsage(AttributeTargets.Class, AllowMultiple=true, Inherited=true)] public class…
Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286
3
votes
1 answer

PostSharp not working on Visual Studio 2015

I have a Visual Studio 2015 solution, into which I have copied-and-pasted a number of PostSharp validation attributes that I had been successfully using on a Visual Studio 2013 project. The project all compiles and runs successfully. …
08Dc91wk
  • 4,254
  • 8
  • 34
  • 67
3
votes
1 answer

Audit windows activity of user on WinFormApplication

I need to implement Audit Trail in my application which is WinForm application. I need to log all the activity done by user on application and in System to see if he had changed any security settings or anything. Is there any way to do this by AOP…
XYZ
  • 119
  • 1
  • 12
3
votes
2 answers

.NET - intercept object without inheritance or Postsharp

I would like to use interception to add logging in my application without having to fill my code with lines like: "Logger.Log(Something);" I am aware this is considered a "Cross-cutting concern" which means it can be well handled using Aspect…
mymo
  • 239
  • 2
  • 11
3
votes
2 answers

Wrapping method call with PostSharp

Is there any way to wrap a method call with PostSharp? I have to add code around/outside a specific call. The OnMethodBound add the code inside the specified method and the MethodInterception aspect redirects the call to the aspect, but I have to to…
Ehler
  • 285
  • 3
  • 11