Steve Collins head shot

Steve Talks Code

Coding thoughts about .NET

Should I be Checking Injected Dependencies for Null?


In this post, I present my Top 5 scenarios of null injections from the .NET Dependency Injection container and use these to justify adding guard clauses to your C# constructors in consuming classes.

Background

I was recently listening to an episode of the Dot Net Core Show with guest Layla Porter (@LaylaCodesIt) on the topic of her brilliant talk TDD and the Terminator. (Go watch the talk and listen to the podcast!)

Around 43 minutes into the podcast, my ears pricked up when Layla mentioned a conversation that we had when she presented the talk at the Dot Net Oxford user group in the UK.

The conversation was instigated by a question (approximately 01:12:00 in the video) regarding whether your code should be checking constructor parameters for null given that the Microsoft Dependency Injection container will throw an InvalidOperationException if it cannot resolve the dependency.

In the podcast, Layla says that she includes null coalesce operations on incoming constructor parameters, primarily out of habit. She then goes on to discuss the arguments as to whether this is testing your code or the injection framework.

Jamie Taylor (host of the podcast) then rightly points out, what if someone instantiates your class directly and not via dependency injection - surely you should do the checks anyway to handle this situation?

This all got me thinking about whether there was anywhere that documents those scenarios when it is possible to receive a null from the container; either directly into a constructor parameter or indirectly, by not populating a class  member within an injected parameter instance.

A quick search on Google did not yield a definitive reference, so I decided I would write this blog post as a one stop shop to define my Top 5 list of when you should consider writing null checking guard clauses in your consuming class' constructor.

"Unresolved Instances Throw an Exception so I Don't Need a Null Check"

So let's start with this statement. On initial consideration, the statement is correct, but there is some nuance to it that needs explaining.

If your consuming class requires an instance of a service type to be resolved by the container and the service type has not been registered, the container will throw an InvalidOperationException. The description within the exception provides details of the service type it was unable to resolve (either directly or indirectly due to a missing registration in the dependency chain).

A couple of other safeguards that are in place include:

  • Registering a singleton using an uninitialised variable/field or a variable/field/class member that results in a null at point of registration will trigger an ArgumentNullException at the registration, prior to the container being built
  • Registering an interface without an implementation will trigger an ArgumentException at the point the container is being built

However, there is a difference between not being able to resolve the service type due to a missing registration and the service type actually being resolved, but returning a null due to something happening within the registration or the instance construction process.

When a service resolves to a null, it will not throw an exception as null may conceptually be a valid result.

"The Way I Registered The Service Will Always Return an Instance"

That may be true at the time you write the registration code. If you are the sole maintainer and sole user of a project, then checking for nulls in the consuming classes may feel like overkill as it is potentially a lot of boilerplate code to write for what may appear to be little gain (though having many constructor parameters is a code smell that may need to be addressed anyway!)

However, source code changes over time or may "rot" so you should consider protecting your consuming class from your future self in case you change the service registration or some other aspect that may affect the dependency resolution.

Why Your Code May Change

If the software you are writing is not just for your own purposes, the potential for change happening in the future increases significantly if:

  • you are working in a team - another member of the team may deliberately change the registration for some reason or inadvertently do so through a source code merge that adds an additional registration that overrides your registration further down in the code
  • you are making use of one or more third party extension methods that do a 'black box' service registration to the IServiceCollection -  these may add one or more overriding registrations after your registration of a service type (note,  by default, the last registration of a service type will be the one that is returned if the consumer asks for a single instance … though if playing nicely, the third party will avoid this by using one of the variations of TryAdd extension methods)
  • you have registered the service type to use a lambda expression that returns the instance by resolving another service registration from the container within the expression
  • you have registered the service type by using a lambda expression that creates the instance for you either within the lambda or by using a factory class.

The other main consideration, (as Jamie said in the podcast),  is that if your class is publicly accessible and has a public constructor, there is nothing to stop someone (either a team member or your future self) from instantiating the instance (via the new keyword).

If this is the case, then it is advisable to put guard checks in place if receiving a constructor parameter set to null will cause your class to either behave differently or, more likely, throw an unexpected NullReferenceException somewhere within its code execution.

My Top 5 Null Injections

So with the above in mind, let's look at some common scenarios I have picked out where the container could resolve a null either for the requested service type or one/some of the properties within a resolved instance.

1. Redirection to Another Service Via the Service Provider

You may have a type that has many interfaces through which you wish the container to resolve an instance (E.g. the Interface Segregation Principle has been applied). In order to ensure each of the interface registrations return the same instance (and not a new instance for each of the interfaces), you need to register the class first and then subsequently register each interface with a lambda expression that uses the service provider to return the main class instance cast as the interface.

So how can this approach end up with the container returning  a null? In short, the lambda expressions are evaluated at runtime when the instance resolution is requested and do not explicitly check for nulls being returned.

However, more specifically with regards to getting another instance from the container, there is just one method, GetService on the IServiceProvider interface to retrieve an instance for you.

If GetService is used within the lambda expression, and the requested type has not been registered, it does not throw an exception. Instead, it will return a null which is then returned from the container to the consumer that requested the service type. Therefore, if the lambda just returns the result from GetService, the consumer will receive a null.

Whilst the IServiceProvider interface only has the one method, the extension methods provided by the ServiceProviderServiceExtensions class include GetRequiredService  and it's generic counterpart GetRequiredService.

These both perform a null check and throw an InvalidOperationException when a service redirection cannot be resolved.

Therefore, my advice is to always use the GetRequiredService extension method if resolving an instance from the container within a lambda.


Another way to get or create instances from the container is the ActivatorUtilities class, but I won't cover that here.


2. Other Lambda Expression Factory Resolutions

In addition to using a lambda expression to resolve another type from the service provider as shown above, we can use the same tactic to resolve an instance from all manner of instance creation methods or lookup systems.

You may be using a dedicated factory class to create an instance or taking some resolved instance and mapping or composing some other type instance from these constituent parts which may inadvertently result in a null.

Similarly, you may be using some form of cache or in memory lookup table that takes a key and returns the result. In some cases, if the value cannot be found, the lookup may return null instead of throwing an exception (E.g. a collection that inherits from NameObjectCollectionBase  or an implementation of IDistributedCache that in turn feeds some data into an object factory).

If this is the case, you may want to consider including a null check within the lambda that will either coalesce the result into a default NullObject instance or throw an exception at point of instance resolution.

If you don't do this, the consumer will need to protect itself from a null parameter injection using guard clauses.

3. Black Box Extensions Methods

Many third party NuGet package libraries offer extension methods to perform service registration of services within the library. In many cases, these become 'black box' service resolutions.

As a consumer of these services, you have no guarantee that the service will not result in a null (due to one or more of the above scenarios).

Whilst you could look at the library source code if it is available on GitHub or though Source Link, this is going beyond what you should need to do as a consumer of a library.

Therefore, as a consumer, you need to protect yourself from null injection if this is going to cause your code to break.


The next two items are not direct null injections, but can cause member values on instances injected from the container to be set to null which may have a knock on consequence on your consuming class.


4. IEnumerable Service Injection

If you (or a third party) have added multiple registrations for the same service type, your consumer will need to specify a constructor parameter of IEnumerable where T is the service type in order to retrieve all the service resolutions.

At time of writing, this is documented on the Microsoft Docs page for DI fundamentals (though this may have moved if you are reading this in the future!)


You can also request multiple services directly from the container using the GetServices extension methods, but again handle with care!


Two things are worth checking when receiving an enumerable of service instances.

Firstly, if the required service type has not been registered, an exception will not be thrown when resolving the enumerable. You will get an IEnumerable  instance (not a null)  but it will not yield any results when iterating over it as it will be empty.

If you cast the (empty) enumerable into an array or a collection based type and have logic that applies some form of matching (on the assumption that certain types have been registered), your code will probably blow up, so it is worth having some guards around this.

Secondly, for the reasons described above in the three direct null scenarios, one (or more) of the services in the returned enumeration may be null and therefore it is worth including a null check guard clause when iterating over the enumerable to confirm that each yielded instance in the enumerable is not null before using it.

5. Configuration Binding

This last source of null injection is an edge case that is not about a null being  injected, but properties on a resolved instance not being set due to a problem with the container.

If you use configuration binding to retrieve a configuration section and bind its children to properties of a class, you could end up with some of the properties (or child properties if hierarchical) being set to default values if the binding is unable to find a match.

This can come about in two ways:

  • The path to the configuration is not found
  • Properties do not have matching entries in the configuration

The first of these scenarios can happen due to errors or source code changes that mean that the whole object cannot mapped as it cannot find the root entry. (E.g. the IConfiguration.GetSection method relies on a string value to specify the section name and therefore any errors in the path will not be detected until runtime)

The second can also happen for the same reasons, but may also happen due to omission of a property within the configuration source (E.g. entry missing from appsettings.json).

Whichever way the mismatch happens, the consuming class need to protect itself from defaults due to the properties not being set (these defaults may be actual values on structs, null for reference types, or an unset nullable value types).

This protection may be done either by coalescing type default values into domain default values or making use of the various validation techniques you can apply to configuration objects that will throw an exception during or post binding.

Alternatively, you could pass the buck down to the end-consumer class to validate the configuration value(s) received.

Guarding Your Consumer Against Null Injection

I have put forward my personal Top 5 list of situations which justify writing guard clauses to check for constructor parameters.

How you perform these checks is up to you, but my approach is to use a mixture of

  • using null coalesce (?? or its C#8 sibling ??= ) into a fixed default value that your code can use
  • check for null injection (or null properties) and throw an ArgumentNullException or (if the context justifies) one of its sibling exceptions (ArgumentException or ArgumentOutOfRangeException). This checking can make use of either an explicit if statement (I like the new C# 9  'is not null' pattern matching); or use the null coalescing operator that throws an exception on null (C# 7.0 onwards)

Whilst you still have to do some work, some of the boilerplate code can be reduced by using a library such as Steve (@ardalis) Smith's GuardClauses NuGet package.

Conclusion

I hope the above list of null injection scenarios has been useful. If I think of any more, I will either post updates to this page or create another post in the future.