I like to add tracing entering and leaving of every methods in classes. and also trace the arguments when an exception occurs. With PostSharp AOP, I don't need to put it in every method but just apply attributes. But I can't afford PostSharp.
Is there an alternate way to do this? Can Unity3D do that?
I am using log4net to log the message.
Yes you can do Aspect Oriented Programming and Interception using Unity.
Unity is a lightweight, extensible dependency injection container with
support for instance and type interception.
There is a great article from Dino Esposito: Aspect-Oriented Programming, Interception and Unity 2.0
Interception in Unity 2.0
The core idea of interception in Unity is enabling developers to customize the chain of calls that it takes
to invoke a method on an object. In other words, the Unity
interception mechanism captures calls being made to configured objects
and customizes the behavior of the target objects by adding some extra
code before, after or around the regular execution of methods.
Interception is essentially an extremely flexible approach to add new
behavior to an object at run time without touching its source code and
without affecting the behavior of classes in the same inheritance
path.
And also there is a great Patterns and Practices article about Interception using Unity.
The example code at article performs logging using interception.
Related
How do you implement multiple inheritance with postsharp?
There is an example here but am new to postsharp. I cant port it to the latest
version of postsharp
The CompositionAspect is still available in the latest PostSharp. You will need to use the newer GetPublicInterfaces method, as well as handle generics differently (see MakeGenericType). We currently don't have samples for this.
However, you can also use IntroduceInterfaceAttribute on an aspect to inject behavior into a type. See PostSharp documentation for details. The aspect introducing the interface provides the implementation of the interface as well, so it would serve as a "base class". Using this, you can create the same pattern as in your example.
Note that true multiple implementation inheritance is not supported by C# or the CLR - these are patterns which allow you to simulate that.
In my app I'm creating an auditing package that obtains various information, one such type of information should provide different information regarding what method is executed (time it took to execute, method name, method class, assembly, etc).
I'm not looking to use an existing package or framework, but to create my own.
I can imagine that this is a complicated thing to do, but I'm looking for some pointers to get me started .
One option you may be interested in is DI-level interception. Since container is responsible for your objects instantiation, sometimes it can be configured with proxy generators to enable call interception.
You can choose between Autofac, or Unity.
The most popular tasks to solve with this approach are cross-cutting concerns, like: logging, measurements, run-time application structure analysis. If you don't want to pollute your code base with repetitive diagnostic code, just delegate this task to an interceptor.
Similiar idea is AOP. I havn't seen popular AOP packages for a long time, and havn't used them, but it's worth to do a research on this topic too:
What is the best implementation for AOP in .Net?
DI Interception vs. AOP
Is there a way of intercepting some method calls without making any code changes around the method itself?
I don't need to inject any custom behaviour at runtime, only add custom performance logging to an existing project.
You want Aspect Oriented Programming.
There are 4 main flavours of AOP
Runtime RealProxy based AOP
Runtime subclass/virtual method AOP
Post Compile IL weave AOP
Precompile source code AOP
The above are ordered in order of speed of execution (slowest to fastest). Note the last two "should" be the same speed. However I expect the compiler to produce better IL than a Post Compile IL weave.
The first camp usually includes IOC containers, since they lend themselves fairly well to this pattern, including and not limited to
Unity
Spring.NET
Castle.Windsor
Postsharp Express
The second camp, is pretty rare, and the only project that I can think of off the top of my head is Entity Framework (which uses it for Lazy loading, however it isn't extensible, and cannot be customised).
The third camp is pretty sparce also, since this technique is extremely complicated and difficult. This works by editing the dll assembly AFTER you have compiled, to add the extra code you want.
Postsharp Pro
Mono.Cecil
Fody (a mono.cecil wrapper)
The final camp is relatively new. So new in fact, the only real entry is the experimental MS Roslyn. This is actually a C# compiler. So...yeah...its pretty magic.
Now, if you are having real huge performance issues with performance critical code, I would suggest using Fody. What is awesome about this, is that it is free (unlike Postsharp Pro), it uses nuget and there is already a performance tool in Fody.MethodTimer.
I have successfully used Castle DynamicProxy for that. It's more lightweight than a full fledged AOP framework, and can be used without an IoC container.
You could take a look at Aspect Oriented Programming, and see if it's a solution for your situation.
For instance:
http://docs.castleproject.org/Default.aspx?Page=Introduction-to-AOP-With-Castle&NS=Windsor&AspxAutoDetectCookieSupport=1
http://fgheysels.blogspot.be/2006/11/aspect-oriented-programming-in-net.html
You can use any AOP Frameworks, like to Spring .NET or Unity, to intercept calls, before or after the method execute.
Thus, you dont need to change your method code.
What you are looking for is Fody: https://github.com/fody
Its open source, stable and has lots of plugins for different AOP use cases.
I am using it in a huge commercial application, and it is working very well.
Installation and configuration is super easy and done within some minutes via nuget.
Some example plugins are:
PropertyChanged: (Injects INotifyPropertyChanged code into properties at compile time)
Anotar (Simplifies logging through a static class and some IL manipulation)
Method Timer (Injects some very basic method timing code)
... and many more!
Requirements, examples and docs can be found on fodys github pages.
Using PostSharp
[Serializable]
public class LogPerformance : OnMethodBoundaryAspect
{
[NonSerialized]
Stopwatch _stopWatch;
public override void OnEntry(MethodExecutionArgs args)
{
_stopWatch = Stopwatch.StartNew();
base.OnEntry(args);
}
public override void OnExit(PostSharp.Aspects.MethodExecutionArgs args)
{
Console.WriteLine(string.Format("[{0}] took {1} ms to execute",
new StackTrace().GetFrame(1).GetMethod().Name,
_StopWatch.ElapsedMilliseconds));
base.OnExit(args);
}
}
Use the aspect like so on a function:
[LogPerformance]
static void LongRunningCalc()
{
//Your Code goes here
}
Simplified from : http://www.codeproject.com/Articles/337564/Aspect-Oriented-Programming-Using-Csharp-and-PostS
We have small lifetime scopes in our applications. It would be interesting to be able to intercept all services registered in autofac. By doing so we can see exactly which path the code takes for every lifetime scope and which method arguments are used. Not really usable for production but when really great for debugging/diagnostics/refactoring as you ge the whole picture and not just unit level.
But AFAIK it's only possible to register an interceptor for each single registration?
Nothing like this is supported out of the box with the Autofac.Extras.DynamicProxy2 library. You could potentially implement something like a module that handles OnActivating for every component using code similar to the stuff in Autofac.Extras.DynamicProxy2, but you'll run into trouble like...
Do you want class interceptors or interface interceptors? The type of service being resolved vs. the limit type of the component backing it will influence what kind of dynamic proxy you want to make. I believe the current A.E.D2 code only generates interception for either/or - not every interface a class implements, etc.
Do you use WCF client proxies? Client proxies are an interesting beast of their own so you have to special-case them. You'll see that in A.E.D2.
Generally problems like this get solved by aspect-oriented programming solutions (e.g., PostSharp) or profilers (e.g., ANTS)... or a combination of both. You might want to look into those solutions if you have the ability.
For an example of what sort of module implementation I'm talking about, check out the log4net integration page on the Autofac wiki. That shows how to handle OnPreparing for every component in the system. You can do the same thing, but handle OnActivating instead and use the sample on the Lifetime Events wiki page to show you how to swap one resolved thing for another (swap the real object for the generated proxy).
I have come to the point where I want to accomplish 2 tasks in my ASP.NET application that both can be done using some AOP framework but they are both of different nature:
Dependency injection for my controllers and services
I have created custom attribute NotNullAttribute and marked some method's parameters or properties with it instead of of throwing ArgumentNullException if those parameters or properties were null. I want AOP framework to check for those attributes in compile time and add throw causes instead. Example follows:
//original code that I write
public void MyMethod([NotNull]string param1){
//do something
}
.
//code actually being compiled - after AOF processing/weaning
public void MyMethod(string patam1){
if(param1 == null){
throw new ArgumentNullException("param1");
}
//do something
}
So I want framework (does not even have to be AOP necessarily but I guess it would have to be) that will allow me to do both those task simply.
I have some additional requirements:
small footprint, 1 or 2 assemblies
integration to VS - I just want to press Ctrl+F5 to compile and the framework does it work, injects dependencies, adds exception throwing code without me even knowing about it. I don't want to run pre-compilation from command line or anything like that.
for exception throwing code generation I'd like write classes. Like regular aspects. Not XML, no configuration (conventions are acceptable). For dependency injection I also prefer classes but XML or another config file is acceptable but it should be simple enough to use by somebody who don't really know XML and don't really like it.
Is there some such framework ? If there are more what are they pros/cons ?
EDIT: Oh yes I forgot very important think: The framework should be for free.
I don't have any personal experience with it, but I think Linfu fits your description.
Apart from that, you can get AOP-like behavior from DI Containers with dynamic interception - here's an example: http://blog.ploeh.dk/2010/09/20/InstrumentationWithDecoratorsAndInterceptors.aspx
The following DI Containers support interception out of the box:
Castle Windsor
Unity
Spring.NET
Pure AOP (without DI) can be had with PostSharp.