Getting Started With PostSharpPostSharp Laos makes aspect-oriented programming easy. You can start writing your own aspect in a matter of minutes. Just follow the guide! 1. Before your forget...Bookmark us with del.icio.us and subscribe to our RSS feed. 2. Download & Install PostSharpYes, you have to download and install! But don't worry, it's only 5 MB. Execute the installer (you will need administrative rights) and restart Visual Studio. 3. Open Your Favorite ProjectLoad one of your projects into Visual Studio 2005 or higher. Any project type will work, but for this example better choose a console application. No matter if you use C#, VB.NET, or another language: it will just work. (Since ASP.NET Web Sites don't use MSBuild, it's a little more difficult with these projects; refer to documentation for details.) 4. Add References To PostSharpYou want to use PostSharp in your project, isn't it? So add a reference to two assemblies: PostSharp.Public.dll and PostSharp.Laos.dll.
5. Create a New Aspect ClassCreate a class and name it TraceAttribute. public sealed class TraceAttribute : Attribute 6. Derive the Class from OnMethodBoundaryIncludes the namespace PostSharp.Laos and make the new class inherit from OnMethodBoundaryAspect. Since this last class derives from System.Attribute, you are actually developing a custom attribute. [Serializable] 7. Implement the HandlersOnce the aspect custom attribute will be applied to a method, this method will invoke the aspect handlers. Do we want to trace methods? So just add trace logic to the handlers! public override void OnEntry( MethodExecutionEventArgs eventArgs ) 8. Apply the Custom Attribute to MethodsIn your project, choose an existing class you want to log and decorate it with our new custom attributes. All methods will be traced. If you prefer to trace some of these methods, don't apply the custom attribute on the class, but on each method. internal static class Program And what if you have a, say, very large assembly? You surely don't want to decorate every method to log, don't you? Well, no problem at all! [assembly: Trace( "MyCategory", AttributeTargetTypes = "My.BusinessLayer.*")]
9. We're done! Compile & ExecuteThat's all, really! If you have a console application, the output should include tracing information.
10. How did it work?Seems magic, huh? Well, to some extent, it is. Open the Output Window of Visual Studio and look at the Build Output: you will see that PostSharp has been invoked. This is the magic wand!
And now, inspect your assembly using .NET Reflector. You will see how PostSharp enhanced your code:
More tutorials like thisThis tutorial is a shorter version of a two-parts article published on codeproject.com. A good way to continue reading about PostSharp! |





