MonoDroid with PostSharp
One of my concerns about my MonoDroid app is that the more features I add, the messier the code is getting. I’m not using an IoC container, for instance, so all my dependencies are hard-wired. I couldn’t figure out a way to hook up one of the great IoC containers out there already (StructureMap, Ninject, etc) without resorting to the service-locator pattern, which really doesn’t get my code less messy (though it does prevent hard dependencies).
With that in mind, I looked to figure out a way to get ‘hooks’ into my app somehow to provide a central place to wire up my dependencies and inject them where necessary. My first thought was to use PostSharp. While this approach may or may not ultimately be the best one, PostSharp is such a terribly useful tool, that I’m bound to want to use it for something else anyway. A quick glance at PostSharp docs indicated that it might be Mono compatible, but what about MonoDroid?
I fiddled with it for a while, posted on both the MonoDroid mailing list and the SharpDevelop forums, fiddled some more, and with some help from Gael, got it working rather easily.
Step 1: Download and install PostSharp.
Step 2: Add a reference to PostSharp.SL.dll to your MonoDroid project. Yes, you read that right, the Silverlight PostSharp library.
Step 3: Add a file PostSharp.Custom.targets to your MonoDroid project with the following contents:
Step 4: Compile. At this point, you shouldn’t be getting a build error, and you should probably get a ‘warning’ message from PostSharp in your VS output window saying that you don’t have any aspects yet, dummy!
Step 5: Create an aspect. Here’s a (pretty useless) sample aspect that I used to test with:
Step 6: Use the aspect. In my case, it was simple as decorating an arbitrary method with the aspect attribute that I just created.
Step 7: Done! You can now use all the PostSharp AOP goodness in your MonoDroid app that you want to. Below is a logcat screenshot of my aspect in action.
Note that this scenario (PostSharp on MonoDroid) is not supported officially by SharpCrafters, so if you run into any problems, you’re more or less on you’re own. Gael was kind enough to push me in the right direction, and he might help you too, but don’t count on it.

Cool post!
I haven’t used postsharp, but I’m interested in IL rewriting. Lets meet up and chat about it at CodeMash.
Definitely. I’ll be “co-presenting” with Bill Sempf at his Monodroid session, but I’m thinking about doing an open session too, since there is so much content to talk about.