Applying Aspect Oriented Programming - c#

I've been using some basic AOP style solutions for cross-cutting concerns like security, logging, validation, etc. My solution has revolved around Castle Windsor and DynamicProxy because I can apply everything using a Boo based DSL and keep my code clean of Attributes. I was told at the weekend to have a look at PostSharp as it's supposed to be a "better" solution. I've had a quick look at PostSharp, but I've been put off by the Attribute usage.
Has anyone tried both solutions and would care to share their experiences?

Couple of minor issues with PostSharp...
One issue I've had with PostSharp is that whilst using asp.net, line numbers for exception messages are 'out' by the number of IL instructions injected into asssemblies by PostSharp as the PDBs aren't injected as well :-).
Also, without the PostSharp assemblies available at runtime, runtime errors occur. Using Windsor, the cross-cuts can be turned off at a later date without a recompile of code.
(hope this makes sense)

I only looked at castle-windsor for a short time (yet) so I can't comment on that but I did use postsharp.
Postsharp works by weaving at compile time. It ads a post-compile step to your build where it modifies your code. The code is compiled as if you just programmed the cross cutting concerns into you code. This is a bit more performant than runtime weaving and because of the use of attributes Postsharp is very easy to use. I think using attributes for AOP isn't as problematic as using it for DI. But that's just my personal taste.
But...
If you already use castle for dependency injection I don't see a good reason why you shouldn't also use it for AOP stuff. I think though the AOP at runtime is a bit slower than at compile time it's also more powerful. AOP and DI are in my opinion related concepts so I think it's a good idea to use one framework for both. So I'll probably look at the castle stuff again next project I need AOP.

Related

AOP Vs Meta-Programming

Is there any difference between AOP and Meta-Programming?
Can we say that meta-programming techniques(IL-weaving, dynamic sub-classing etc.) are mechanisms to achieve AOP which is more about separation of cross-cutting concerns from main application code concerned with actual business requirements?
As I see it, metaprogramming is just a way to make AOP work without explicit support for it.
AOP could be implemented without metaprogramming, if your platform specifically supported it. And metaprogramming can be used for many other things than just AOP.

AOP performance overhead

I've been searching a bit for some performance tests about typical AOP tasks. I've not been able to find any though, could you help me?
I'm mostly thinking about Castle, Unity and perhaps PostSharp, even though it might be too expensive for my project.
I haven't seen any quantitative comparisons, too, so this answer is probably far from being complete.
It is difficult to compare performance of Castle or Unity with PostSharp - Castle and Unity use runtime weaving by dynamic proxying and PostSharp adds overhead at compile stage. So if performance is crucial for you, compiled solutions like PostSharp will always be better. Generating AOP proxies in runtime means dynamic generating IL code and heavy reflection use.
So performance tests that could make sense have to compare solutions using the same technique - you can try to compare Castle Dynamic Proxy and Unity Interception proxy implementation.
I don't know the former well, but in case of latter, there are still three different scenarios to compare - transparent proxies (MarshalByRefObject), interface proxies and subclassing proxies - each with its own set of usage scenarios and its own performance overheads. From what I've read, transparent proxy is horribly slow and shouldn't be used in AOP scenarios. Interface and subtyping proxies generates some IL on the fly and this is the same what Castle DP does so I believe the differences shouldn't be so big (but again, no quantitative results here).
If you are looking for a light weight AOP tool, there is a article "Add Aspects to Object Using Dynamic Decorator" (http://www.codeproject.com/KB/architecture/aspectddecorator.aspx). It is thin and flexible.
It describes an approach to adding aspects to object at runtime instead of adding aspects to class at design time. The advantage of this approach is that you decide if you need an aspect when you use an object.
Most of today's AOP tools define aspects at class level at class design time. And you don't have the flexibility when you use an object of the classes.
If performance is crutial in your project, make sure your usage of the AOP is performance oriented because the overhead of an AOP Framework is rarely poor unless the usage is not compliant.
For example, if you use DynamicProxy, you have the choice to call the backing treatment using reflection or calling Proceed() method. It alter differently performance.
Another example : most of AOP Framework give you the MethodInfo to your "advice". The way how they get this metedata can alter your performance because GetMethodFromHandle can be very bad in extremely concurrency treatments (dictionary access with a lock).
Another important thing to keep in mind : use the adapted overlod for Advice method because if AOP Framework have to prepare too much informations (argument, methodinfo, ...) You will pay it (performance overhead). Unfortunely, sometimes there is no good user end interface to implement a performant advice event if interception was perfect.
For more details, in the post when-is-aop-code-executed, I give my feedback about performance issue of AOP Framework.

Do you use NDepend?

I've been trying out NDepend, been reading a few blogposts about it and even heard a podcast. I think that NDepend might be a really useful tool, but I still don't see where I would use it.
How do you use it? Do you use it, why? Why not?
I would like to hear about some down-to-earth real world examples.
I've used NDepend extensively over the past few years. Basically it is a dependency analysis tool, and so this can help you with lots of dependency related issues.
One of the main things I use it for is to examine the dependencies between my assemblies, types and methods. This helps me to keep a view of whether coupling between types is out of hand, and also helps me spot refactoring opportunities.
When embarking on a massive refactor, e.g. extracting.moving types to other assemblies, this lets you see what depends on what so you don't have to do the old "move my types to another assembly, then try and compile and see what breaks"
NDepend also has a great visual matrix for viewing this sort of information.
Additionally, it has a fantastic query language, CQL, which lets you write custom queries. These can be simple things such as "show me all methods that call this method", to queries to highlight dead code, queries on cylcomatic complexity, coupling, etc, and much much more.
In turn, it can be integrated into a build process, so you can have build warnings/failures based on CQL queries, such as "fail the build if a method has more than 100 lines of code but no comments" (this is an example - I'm not suggesting this particular metric is a good thing).
It can also import code coverage data and give you a visual representation of areas with little code coverage, as well as allowing you to run CQL queries against code coverage information (e.g. show me methods with less than 70% code coverage)
You can also load your current build of your project, and a previous build, and run queries between them such as "show me all new types that have <70% code coverage" - this helps you introduce tighter rules on existing codebases.
This is a fantastic tool, and isn't too difficult to learn. It is scary at the start, just because of the sheer volume of informaiton it gives you, but is highly recommended.
I also find it invaluable in understanding the structure of complicated method calls. I can call up all methods transitively using a particular method or field, for example, and can see if there are possible problems with circular calls, or unwanted dependencies, or paths which are more convoluted than necessary, etc.
The dependency graph is also now interactive, so I can remove methods which I am not currently interested in, and move others around to give a good visualization of what is going on.
I've found it useful to visualize changes between versions of assemblies. Even for a snapshot of changes in a given release...
I think it shines in a Continuous Integration environment where you can set up CQL queries to measure code metrics you're interested in (Cyclomatic Complexity, Long Methods, etc.), and then you can measure your improvement in those areas over time.
Actually this tool is helpful if you have e.g. interface which is using by another part of application developed by different person/vendor. Everytime you want to change the interface you have to find out who is using your interface to avoid breaking its code (assembly won't build)
This is applicable for bigger projects.
This tool is helpful when your application has a huge number of assemblies.
It helps me find out the code dependencies and as well as changes between releases
I'm also using NDepend to compare two versions of some assembly. NDepend have this excelent feature. Thats gives me view about changes and work progress in assembly, methods that have been added, methods removed and many more.

Code protection and code weaving in .net

I tried to use code protection (code is encrypted and can't be reflected) made by clisecure with postsharp but secured dlls won't compile when post sharp is used in solution. I use just PostSharp.Laos and PostSharp.Public
Have You ever tried such combination? Did you manage to make it work. If so please tell what obfuscation tool and what code weaving framework have you been using?
I have successfully used Dotfuscator and Postsharp in combination but only with the compile time IL Weaving and not yet with any runtime interception. Everything should be fairly straightforward as long as you obfuscate the binary that PostSharp post-compilation weaving outputs.
The usual obfuscation caveats apply to any of your cross cutting code (especially where you use reflection) as obfuscation changes symbol names and you will need to exclude any symbols from being renamed or pruned that will be reflected upon or that use late binding.
There are some tricks when using an obfuscator. For instance, you cannot change the name of aspect types and fields of aspect types because aspect are serialized by PostSharp and deserialized at runtime. You may want to use obfuscation exceptions for aspects.
Another issue is that you cannot rename some methods that are the target of aspects. I think this happens only with generic methods or methods of generic types.
An alternative is to use an obfuscator that does not rename the code, such as WIBU. I did not try, however.

Which .NET Dependency Injection frameworks are worth looking into? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Which C#/.NET Dependency Injection frameworks are worth looking into?
And what can you say about their complexity and speed.
edit (not by the author): There is a comprehensive list of IoC frameworks available at https://github.com/quozd/awesome-dotnet/blob/master/README.md#ioc:
Castle Windsor - Castle Windsor is best of breed, mature Inversion of Control container available for .NET and Silverlight
Unity - Lightweight extensible dependency injection container with support for constructor, property, and method call injection
Autofac - An addictive .NET IoC container
DryIoc - Simple, fast all fully featured IoC container.
Ninject - The ninja of .NET dependency injectors
Spring.Net - Spring.NET is an open source application framework that makes building enterprise .NET applications easier
Lamar - A fast IoC container heavily optimized for usage within ASP.NET Core and other .NET server side applications.
LightInject - A ultra lightweight IoC container
Simple Injector - Simple Injector is an easy-to-use Dependency Injection (DI) library for .NET 4+ that supports Silverlight 4+, Windows Phone 8, Windows 8 including Universal apps and Mono.
Microsoft.Extensions.DependencyInjection - The default IoC container for ASP.NET Core applications.
Scrutor - Assembly scanning extensions for Microsoft.Extensions.DependencyInjection.
VS MEF - Managed Extensibility Framework (MEF) implementation used by Visual Studio.
TinyIoC - An easy to use, hassle free, Inversion of Control Container for small projects, libraries and beginners alike.
Stashbox - A lightweight, fast and portable dependency injection framework for .NET based solutions.
Original answer follows.
I suppose I might be being a bit picky here but it's important to note that DI (Dependency Injection) is a programming pattern and is facilitated by, but does not require, an IoC (Inversion of Control) framework. IoC frameworks just make DI much easier and they provide a host of other benefits over and above DI.
That being said, I'm sure that's what you were asking. About IoC Frameworks; I used to use Spring.Net and CastleWindsor a lot, but the real pain in the behind was all that pesky XML config you had to write! They're pretty much all moving this way now, so I have been using StructureMap for the last year or so, and since it has moved to a fluent config using strongly typed generics and a registry, my pain barrier in using IoC has dropped to below zero! I get an absolute kick out of knowing now that my IoC config is checked at compile-time (for the most part) and I have had nothing but joy with StructureMap and its speed. I won't say that the others were slow at runtime, but they were more difficult for me to setup and frustration often won the day.
Update
I've been using Ninject on my latest project and it has been an absolute pleasure to use. Words fail me a bit here, but (as we say in the UK) this framework is 'the Dogs'. I would highly recommend it for any green fields projects where you want to be up and running quickly. I got all I needed from a fantastic set of Ninject screencasts by Justin Etheredge. I can't see that retro-fitting Ninject into existing code being a problem at all, but then the same could be said of StructureMap in my experience. It'll be a tough choice going forward between those two, but I'd rather have competition than stagnation and there's a decent amount of healthy competition out there.
Other IoC screencasts can also be found here on Dimecasts.
It depends on what you are looking for, as they each have their pros and cons.
Spring.NET is the most mature as it comes out of Spring from the Java world. Spring has a very rich set of framework libraries that extend it to support Web, Windows, etc.
Castle Windsor is one of the most widely used in the .NET platform and has the largest ecosystem, is highly configurable / extensible, has custom lifetime management, AOP support, has inherent NHibernate support and is an all around awesome container. Windsor is part of an entire stack which includes Monorail, Active Record, etc. NHibernate itself builds on top of Windsor.
Structure Map has very rich and fine grained configuration through an internal DSL.
Autofac is an IoC container of the new age with all of it's inherent functional programming support. It also takes a different approach on managing lifetime than the others. Autofac is still very new, but it pushes the bar on what is possible with IoC.
Ninject I have heard is more bare bones with a less is more approach (heard not experienced).
The biggest discriminator of Unity is: it's from and supported by Microsoft (p&p). Unity has very good performance, and great documentation. It is also highly configurable. It doesn't have all the bells and whistles of say Castle / Structure Map.
So in summary, it really depends on what is important to you. I would agree with others on going and evaluating and seeing which one fits. The nice thing is you have a nice selection of donuts rather than just having to have a jelly one.
Autofac. https://github.com/autofac/Autofac It is really fast and pretty good. Here is a link with comparisons (made after Ninject fixed a memory leak issue).
http://www.codinginstinct.com/2008/05/ioc-container-benchmark-rerevisted.html
Ninject is great. It seems really fast, but I haven't done any comparisons. I know Nate, the author, did some comparisons between Ninject and other DI frameworks and is looking for more ways to improve the speed of Ninject.
I've heard lots of people I respect say good things about StructureMap and CastleWindsor. Those, in my mind, are the big three to look at right now.
I use Simple Injector:
Simple Injector is an easy, flexible and fast dependency injection library that uses best practice to guide your solutions toward the pit of success.
I'm a huge fan of Castle. I love the facilities it also provides beyond the IoC Container story. It really simplfies using NHibernate, logging, AOP, etc. I also use Binsor for configuration with Boo and have really fallen in love with Boo as a language because of it.
I spent the better part of a day struggling without success to get the simplest Spring.NET example working. Could never figure out how to get it to find my assembly from the XML file. In about 2 hours, on the other hand, I was able to get Ninject working, including testing integration with both NUnit and MSTest.
I've used Spring.NET in the past and had great success with it. I never noticed any substantial overhead with it, though the project we used it on was fairly heavy on its own. It only took a little time reading through the documentation to get it set up.
I can recommend Ninject. It's incredibly fast and easy to use but only if you don't need XML configuration, else you should use Windsor.
The great thing about C# is that it is following a path beaten by years of Java developers before it. So, my advice, generally speaking when looking for tools of this nature, is to look for the solid Java answer and see if there exists a .NET adaptation yet.
So when it comes to DI (and there are so many options out there, this really is a matter of taste) is Spring.NET. Additionally, it's always wise to research the people behind projects. I have no issue suggesting SourceGear products for source control (outside of using them) because I have respect for Eric Sink. I have seen Mark Pollack speak and what can I say, the guy just gets it.
In the end, there are a lot of DI frameworks and your best bet is to do some sample projects with a few of them and make an educated choice.
Good luck!
I think a good place to start is with Ninject, it is new and has taken into account alot of fine tuning and is really fast. Nate, the developer, really has a great site and great support.
Spring.Net is quite solid, but the documentation took some time to wade through. Autofac is good, and while .Net 2.0 is supported, you need VS 2008 to compile it, or else use the command line to build your app.

Categories

Resources