Search code examples
c#inversion-of-controlioc-container

Creating a small IoC Container in C#


I decided to create a very small IoC container in C# for a MonoGame project. The reason i decided to create one myself is to improve the performance and use less libraries that i don't control. Since IoC is something so simple, i don't think a library should handle it.

I started a naive implementation:

var container = new Container();
container.Register("service-alias",
    container => new ServiceClass(container.Resolve("other.dep"));

container.Resolve("service-alias").MethodOnServiceClass()

But I have no idea how to do this in C#'s type system. A Dictionary <string, Func<Container>>? How do I type the return of the resolve method?


Solution

  • Here is an example implementation with 21 lines of code. But please don't be tempted to simplify development by implementing some dictionary that holds the registrations (other than doing so for educational purposes). There are many downsides to hand rolling your own DI library. As explained here, you are much better of by applying Pure DI (which means: DI without DI library) and switching from Pure DI to a DI library later on, in case -and ONLY in case- your Composition Root becomes hard to maintain without.