I’ve previously written about the Scrutor library. However, this post covers something that has long irritated me about using an IoC container. Typically, when you have a fairly complex site, you’ll end up with dozens of statements like the following:
builder.Services.AddScoped<ISearchService, SearchService>(); builder.Services.AddScoped<IResourceDataAccess, ResourceDataAccess>();
It turns out that one of the other things that Scrutor can do for you is to work out which dependencies you need to register. For example, let’s consider the two classes above; let’s say that the first is in the main assembly of the project:
builder.Services.Scan(scan => scan .FromCallingAssembly() .AddClasses(true) .AsMatchingInterface() .WithScopedLifetime());
So, what does this do?
Well, FromCallingAssembly points it at the main assembly (that is, the one which you’re calling this registration from). FromClasses(true) then returns a list of all public classes and interfaces.
Finally, AsMatchingInterface matches classes with their interfaces, assuming a one-to-one pairing (if you don’t have that then there are other options to cope with that); and WithScopedLifetime will register them as scoped.
That worked well, but when I ran it, I realised that the second class (ResourceDataAccess) hadn’t registered. The reason being that it wasn’t from the calling assembly, but lived in a referenced project. An easy way to fix this was:
builder.Services.Scan(scan => scan .FromCallingAssembly() .AddClasses(true) .AsMatchingInterface() .WithScopedLifetime() .FromAssemblyOf<IResourceDataAccess>() .AddClasses(true) .AsMatchingInterface() .WithScopedLifetime());
Notice that we can simply return to the start following the With…Lifetime(), and this time, we tell it to register any classes found in the same assembly as IResourceDataAccess.
If we look at the list of assemblies, we can see this has worked:
What this means is that, each time you add a new class, you don’t have to add a registration in the startup / program file. This is perhaps a good and bad thing: arguably, if the list gets so large that it’s noticeable, then you might have gauged your decomposition incorrectly.