This article introduces the new ThunderboltIoc framework that achieves dependency injection in .NET without reflection. You will find the documentation as well as a quick-start guide to walk you through the framework.
Introduction
One of the very first IoC frameworks for .NET that has no reflection. An IoC that casts its services before thunder casts its bolts. 😄
The goal is to create a code-generation based IoC container for .NET. Almost all containers today rely on reflection to provide a functioning IoC, which is a costly operation. Regardless of the valued attempts to improve the performance of these containers over the years, these containers would not match the performance of a code-generation based IoC, if that could be achieved. It is quite irritating to witness the cost we pay for trying to clean our code by -among other things- using a reflection-based IoC framework and being able to do nothing about it. The idea is to let the user (the developer) write their code as they please, and let the IoC take care of code generation during compilation to provide a working and performant solution in the target assembly.
I have finally managed to find the time to start working on the solution. Fortunately for me and for the community, I read about source generators in .NET before starting. Having watched the power of source-generators combined with the power of Roslyn, I decided to pick that path over other approaches such as T4 templates and CodeDom for code generation, and I'm glad I made that choice. Mine might not be the first solution to follow this approach, but I like to think of it as the most powerful and flexible one to-date.
Below is a documentation as well as features overview and a quick-start guide to walk you through the framework. You may find the full source code on the GitHub repository.
I'm also open to your suggestions. Feel free to contact me by leaving a message below.
P.S.: The phrase "if that could be achieved" did exist in my original pretext in March 2021. Even though I managed to make this true today, I decided to keep it here as further motivation for the reader.
Table of Contents
- Installation
- Make sure that you're using C# version 9.0 or later
- Implement ThunderboltRegistration as a partial class
- Quick Start
- Anywhere in your assembly FooAssembly
- At your startup code
- Using your services
- Features Overview
- Benchmarks
- Service Lifetimes
- Singleton
- Scoped
- Transient
- Service registration
- Services registered for you by default
- Explicit registration
- Same service and implementation type
- Different service and implementation types
- The service has a factory to determine the resulting instance
- The service has runtime logic to determine its implementation
- Attribute Registration
- ThunderboltIncludeAttribute
- ThunderboltExcludeAttribute
- Regex-based Attribute (convention) Registration
- ThunderboltRegexIncludeAttribute
- Registering services that they themselves represent their own implementation
- Registering services that have different type for their implementation
- IFooService: FooService: For the common scenario where we may want to match IFooService with FooService
- ThunderboltRegexExcludeAttribute
- How to Resolve/Get Your Instances
- Obtaining an IThunderboltContainer
- Obtaining an IThunderboltScope
- Supported Project Types
- Known Limitations
- Planned for Future Versions
- Finally!
- History
ThunderboltIoc's installation is a simple as installing the nuget to the target assemblies. No further configuration is needed. For the sake of registering your services, however, you're going to need to implement (i.e., create a class that inherits) ThunderboltRegistration
as a partial class in each project where you may want to register services. You may find the package at Nuget.org: using dotnet:
dotnet add package ThunderboltIoc
or using Nuget Package Manager Console:
Install-Package ThunderboltIoc
In each of your projects where ThunderboltIoc is referenced, make sure that the C# version used is 9.0
or later. In your *.csproj add:
<PropertyGroup>
<LangVersion>9.0</LangVersion>
</PropertyGroup>
Please note that C# 9.0 is supported only in Visual Studio 2022, and Visual Studio 2019 starting from version 16.7
.
This step is not needed if you don't have any types/services that you would like to register in this assembly. However, if you do (which is likely), you should create a partial class that implements the ThunderboltRegistration
abstract
class. More on the registration can be found in the relevant section of this document.
After installation, here's a minimal working example:
public partial class FooThunderboltRegistration : ThunderboltRegistration
{
protected override void Register(IThunderboltRegistrar reg)
{
reg.AddSingleton<BazService>();
reg.AddScoped<IBarService, BarService>();
reg.AddTransientFactory<Qux>(() => new Qux());
}
}
Where this code may execute before any attempt to resolve/get your services.
ThunderboltActivator.Attach<FooThunderboltRegistration>();
The simplemost way to get your services would be as follows:
BazService bazService = ThunderboltActivator.Container.Get<BazService>();
- Achieving dependency injection in .NET without reflection, based on Roslyn source generators, with a simple and intuitive API
- Being able to register your services with three different lifetimes: Singleton, Scoped and Transient
- Explicit registration where you instruct the framework to register a particular service
- The ability to register services while specifying user-defined factories for their creation while maintaining their lifetimes
- The ability to register services while specifying user-defined logic to determine the type of the service implementation
- Attribute-based service registration where you can use attributes to register or exclude types
- Registration by convention where we can register services by naming convention using regular expressions
The src/benchmarks project uses BenchmarkDotNet to conduct measured performance comparison between ThunderboltIoc and the following dependency injection frameworks:
-
Microsoft.Extensions.DepdendencyInjection (on nuget.org) - benchmarks legend: MicrosoftDI The industry-standard dependency injection framework for .NET provided by Microsoft that offers basic set of features at a high performance. It relies on runtime expression compilation for services creation.
-
Grace (on nuget.org) - Known for its wide range of features offered at a superior performance. It depends on System.Reflection.Emit
runtime code generation for creating services.
It is worth mentioning that iOS does not support runtime code generation and therefore Grace's options are limited when it comes to Xamarin apps or client-side apps in general.
-
Autofac (on nuget.org) - Famous and known for its rich features. It uses raw reflection to instantiate services, but that comes at a grievous cost as the benchmarks show.
Despite being new, ThunderboltIoc attempts to combine the best of each of these frameworks and avoid the worst, with an optimum memory usage. The benchmarks run multiple times with different run strategies and measure the performance of each framework in terms of startup and runtime, where startup is what it takes to fully create and configure the container, and runtime is what it takes to get/resolve/locate few services.
I will first share an example run of the benchmarks on my machine, and then few insights on what the numbers mean.
Click to enlarge images
The data above is sorted by the mean column from the fastest to the slowest. The mean however can be (and is) affected by few outliers, which is why I have included baseline ratio and median columns. Some of the medians in the data above provide evidence on the fact their corresponding means are affected by outliers.
However, in order to have a more accurate insight as to which framework performs better in which scenario, we should look at the ratio column. ThunderboltIoc will always have one and in each scenario, the other frameworks will have proportional values where a smaller value means better performance in this scenario and a bigger value means worse performance in that scenario.
For those who might not be familiar with BenchmarksDotNet, the ratio is often confused with final means proportional to each other. That is not true. Instead, in each run, the ratio is calculated and stored for this particular operation, and in the end, the ratio displayed will be the mean of all the ratios calculated. This provides better immunity against outliers.
It is also worth mentioning that the allocated memory for ThunderboltIoc prevails (or equals the minimum) in each scenario.
Thunderbolt's service lifetimes are very similar (or in fact, almost identical) to those of Microsoft.Extensions.DependencyInjection
that was first introduced with .NET Core.
Specifies that a single instance of the service will be created throughout your program’s lifecycle.
Specifies that a new instance of the service will be created for each scope. If no scope was available at the time of resolving the service (i.e., the IThundernoltResolver
used was not an IThunderboltScope
), a singleton service will be returned.
If a service gets resolved using an IThunderboltScope
as the IThunderboltResolver
, each and every scoped dependency of that service will be resolved using the same IThunderboltScope
(unless it was a singleton service whose scope dependencies had been resolved earlier).
Specifies that a new instance of the service will be created every time it is requested.
As well as services registered for you by default, here are three ways in which you may register your assemblies:
- Explicit registration
- Attribute registration
- Regex-based attribute registration
All the three of them are valid to use either alone or in conjunction with any other. In fact, the source generator generates explicit registrations for attribute registrations.
-
IThunderboltContainer
: The container itself is registered as a singleton service. In fact, even ThunderboltActivator.Container
that you may use to get the container returns the same singleton instance.
-
IThunderboltScope
: This is registered as a transient service, meaning, every time you try to resolve/get an IThunderboltScope
, a new IThunderboltScope
will be created. This is the same as IThunderboltContainer.CreateScope()
.
It is worth mentioning that an IThunderboltScope
is an IDisposable
, however, that doesn't mean that disposing an IThunderboltScope
would dispose scoped instances (at least in the current release).
-
IThunderboltResolver
: This is registered as a transient service and returns IThunderboltResolver
that was used to get this instance. This will only ever return IThunderboltContainer
or IThunderboltScope
.
After you have created a partial class that inherits ThunderboltRegistration
, you will have to override the abstract void Register
. This method gives you a single argument of type IThunderboltRegistrar
(reg
), which you can use to register your services using the Add{serviceLifetime}
methods.
For explicit registration, code generation is going to happen for every Add{serviceLifetime}
call that happens inside (except for factory registrations), regardless of whether or not you implement a logic in your Register method (i.e., even if you implement a logic where a particular call to an Add
method is not reachable, code generation would still consider it anyway).
Explicit registration supports four different scenarios for registering your services.
For this scenario, you may register your services like:
reg.AddSingleton<FooService>();
reg.AddScoped<BarService>();
reg.AddTransient<BazService>();
For this scenario, you may register your services like:
reg.AddSingleton<IFooService, FooService>();
reg.AddScoped<IBarService, BarService>();
reg.AddTransient<IBazService, BazService>();
For this scenario, you may register your services like:
reg.AddSingletonFactory<FooService>();
reg.AddScopedFactory<BarService>();
reg.AddTransientFactory<BazService>();
In this scenario, no code generation happens at all as it is assumed that you are going to provide all the necessary details to get an instance of this service. Service lifetimes however would still apply to service registered using any of the factory signatures.
For this scenario, you may register your services like:
reg.AddSingleton<IYearHalfService>(() =>
{
if (DateTime.UtcNow.Month <= 6)
return typeof(YearFirstHalfService);
else
return typeof(YearSecondHalfService);
});
In this scenario, it is important to know that code generation happens for every capture of the statement return typeof(TService)
inside the scope. This means that your implementations must be known at the compile time. It is also important to notice that either this:
Type fooType = typeof(FooType);
return fooType;
or that:
return someFooVariable.GetType();
will not work.
Also, you cannot pass a function pointer to this signature. It will compile but it won't work. The only accepted syntaxes are lambda expressions (e.g., () => typeof(TService)
or () => { return typeof(TService); }
) and anonymous method expressions (e.g., delegate { return typeof(TService); }
).
This is where you may register your services using attributes. It is important to know that even if you don't have any explicit registrations, you still need to create a partial class that inherits ThunderboltRegistration
for attribute registration to work. Attribute registrations are managed via two attributes (+ the regex ones): ThunderboltIncludeAttribute
and ThunderboltExcludeAttribute
.
Define this attribute at the top of the types you want to register. There are few signatures for this attribute but they all come down to three simple arguments.
serviceLifetime
(required): Specifies the service lifetime you want to register for this service. implementation
(optional): If this service has another type as its implementation, this is how you may specify that. applyToDerviedTypes
(optional, default: false
): Determines whether derived types should also be registered just like this service. It is important to note that captured derived types are limited only to the types that are accessible in the assembly that defines the attribute; meaning: if you have an assembly FooAssembly
where you use ThunderboltIncludeAttribute
(with applyToDerivedTypes
: true
), and another assembly BarAssembly
that references FooAssembly
but also defines some derived types, types in BarAssembly
will not be registered (unless another ThunderboltIncludeAttribute
is defined in BarAssembly
as well).
Specifies that this type will not be registered unless it gets registered explicitly via ThunderboltRegistration.Register
(even if ThunderboltIncludeAttribute
or ThunderboltRegexIncludeAttribute
is present).
This attribute also has the optional parameter (default: false
) applyToDerivedTypes
which specifies that derived types accessible in this assembly should not be registered via attribute-registration attributes.
This is how you may register several services at once, using their naming convention. Just like non-regex attribute registration, it is important to create a partial class that inherits ThunderboltRegistration
for this to work, even if you don't have any explicit registrations. Regex attribute registrations are managed via two attributes: (ThunderboltRegexIncludeAttribute
and ThunderboltRegexExcludeAttribute
).
Attributes used for regex-based registration are assembly-level attributes (they should be defined on the target assembly [assembly: ThunderboltRegexIncludeAttribute(...)]
).
This is where you define your conventions for naming-convention-based registration. The first argument passed to this attribute is the service lifetime for all the services matched by this attribute.
The regex argument passed to the attribute should match all the types that you wish to register. Your pattern is tested against the full names of the types (global::Type.Full.Namespace.TypeName
).
Beware that your pattern gets tested against all of the accessible types, meaning that you may want to write a pattern that does not include types defined under the System namespace for instance.
You may have several ThunderboltRegexIncludeAttribute
on the same assembly to define different patterns and lifetimes.
Using only the two arguments discussed above is going to be sufficient for this scenario.
For this scenario, two more arguments are going to be needed in addition to the lifetime and the regex.
implRegex
: This should be a regular expression that matches all of your implementation types (and only your implementation types). joinKeyRegex
: By now, your regex argument should be matching a number of services, and your implRegex
argument should be matching a number of service implementations. This parameter is used to select a particular join key from the results matched by both of your other arguments to determine which implementations correspond to which services. This is also a regular expression.
[assembly: ThunderboltRegexInclude(
ThunderboltServiceLifetime.Scoped,
regex: @"(global::)?(MyBaseNamespace)\.I[A-Z][A-z_]+Service",
implRegex: @"(global::)?(MyBaseNamespace)\.[A-Z][a-z][A-z_]+Service",
joinKeyRegex: @"(?<=(global::)?(MyBaseNamespace)\.I?)[A-Z][a-z][A-z_]+Service")]
This is where you may specify a regular expression that when matched with any type, does not get registered via attribute registration (and/or regex-based attribute registration).
Getting service instances with respect to their registered lifetimes is as simple as using Get<TService>()
on an IThunderboltResolver
. An IThunderboltResolver
may either be an IThunderboltContainer
or an IThunderboltScope
.
Provided you have attached at least one partial class that inherits ThunderboltRegistration
via ThunderboltActivator.Attach
, it is safe to use ThunderboltActivator.Container
property to get the singleton IThunderboltContainer
instance. If you already have an IThunderboltResolver
, you may also get the same container using resolver.Get<IThunderboltContainer>()
.
Using an IThunderboltContainer
, you may create a new scope using container.CreateScope()
. If you already have an IThunderboltResolver
, you may create a new scope using resolver.Get<IThunderboltScope>()
.
All project types are inherently supported and your project wouldn't complain about working with ThunderboltIoc
. However, up until the moment of writing this, there is no explicit integration with Microsoft.Extensions.DependencyInjection
, which to some extent limits our options when working with .NET Core projects if we wanted to utilize Microsoft's DI.
It is intended for ThunderboltIoc
to integrate with Microsoft.Extensions.DependencyInjection
in the future, but it the meantime, there would be no harm in using both frameworks together side-by-side; that however wouldn't let us fully benefit from ThunderboltIoc
's superior performance all the time.
It is perfectly safe to use ThunderboltIoc
for any .NET C# project as a standalone IoC.
The only services for which code generation can work are services that have exactly one constructor that is public
. It is planned to lift this restriction in future versions.
As mentioned in the section above, it is feasible and desired to remove this limitation.
Currently, in the best-case scenario and if you follow the documentation, we shouldn't worry about source generation exceptions. However, upon failing to adhere to the documentation, it is possible that an unhandled exception might arise. In such a case, the source generator might (or might not) fail at the whole process. When that happens, it is possible that no code gets generated at all (you would get a notification in the build output but you might not notice it).
It is planned to provide better exception handling so that failure to generate code for a particular service wouldn't cause the whole process to fail. It would also be nice to generate relevant warnings or errors.
Currently, it is possible to fall into an infinite resolve operation where one (or more) service's dependencies may directly or indirectly depend on the same service.
It would be beneficial to have static code analyzers that show you warnings about failing to adhere to the best practices discussed in the documentation. For instance, generate a warning that tells you that a class you created that inherits ThunderboltRegistration
does not have the partial modifier.
As is the case with any feature-rich IoC framework, property injection is a dependency injection style that is not currently supported by this framework.
Disposing an IThunderboltScope
should in turn dispose every IDisposable
scoped service saved in the corresponding IThunderboltScope
.
The goal is to provide an intuitive API to effectively replace the default IServiceProvider
of Microsoft's DI. Currently, IThunderboltResolver
already implements System.IServiceProvider
but no present elegant integration exists.
I hope this release make it up to your expectations! I'm really looking forward to hearing your feedback and suggestions in the comments below.
It is my intention to update this article should new releases come out. If interested, you may want to keep an eye on it.
- 18th January, 2022: Initial version