I have been tinkering around my "home brewed" dependency injection library, as I mentioned in my last post. Since most of the code revolves around instantiating objects (well, and keeping them orderly registered), I figured it couldn't hurt to check out which is the best (i.e. fastest) way to dynamically instantiate objects in .NET.
There are essentially two ways you can register objects to my IoC container: using a delegate or using the type. The delegate is a really nice method, also used by Autofac (any comparison between my library and Autofac is probably an insult to Autofac
). It works like this:
container.Register(c => new Implementor());
In this case the delegate simply instantiates an instance of a class that implements the IInterface interface. Pretty slick and also very fast: calling the delegate is exactly one method call slower than calling the new operator, so that shouldn't be a problem at all.
Problem is, sometimes you can't register a delegate (for instance when you're registering dynamically loaded plug-ins to the container). In that case you need to manually instantiate the objects: .NET provides a lot of different ways to do that, and some methods can be compiled to dynamic methods or to delegates which probably should improve their performance.
There's a pretty complete blog post by Haibo Luo, but it's 5 years old and might not be accurate (it also misses the methods that use System.Linq.Expressions).








