In many applications and development teams, dependency injection (or DI) with inversion of control (or IoC) has become standard practice for creating better software design. It allows for loosely coupled modules, better unit tests (or even TDD) and a better implementation of SOLID principles.Over the years we all got
In many applications and development teams, dependency injection (or DI) with inversion of control (or IoC) has become standard practice for creating better software design. It allows for loosely coupled modules, better unit tests (or even TDD) and a better implementation of SOLID principles.
Over the years we all got used to our favorite IoC frameworks; including Autofac, Ninject, Windsor and many others. But, with the release of ASP.NET Core, we now have DI built right into the framework! It is intentionally designed to have less features, lowering the learning curve for those who are unfamiliar with the concept. And, should the built-in IoC container not meet all your needs, a third-party IoC container plugin can be used quite easily.
With this post I would like to show you how you can write "human readable" dependency registrations. While this is framework agnostic, the code samples use the .NET Core DI framework.
If you are unfamiliar with dependency injection in ASP.NET Core, please review the documentation provided by Microsoft here.
So, let's dive in!
We use the IServiceCollection
to do registrations in the Startup
class of the client application. Which looks like this:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(new App("switching-api"));
services.AddDbContext(o =>
o.UseSqlServer(SqlServerConnectionString))
services.AddTransient();
}
As a general practice, move your registration to the responsible layer. If you have a data access layer (DAL), all registrations should be located within its boundaries. This follows the DRY (don't repeat yourself) principle and increases the level of maintainability (remember SOLID).
We can use an extension method to achieve exactly that. In the DB project, we add a file containing the following code:
public static IServiceCollection RegisterDbModule(this IServiceCollection services, string connectionString)
{
services.AddDbContext(
options => options.UseSqlServer(connectionString));
services.AddDbContext(
options => options.UseSqlServer(connectionString));
services.AddTransient();
services.AddTransient();
return services;
}
All the DB related registrations are moved to the DAL. Our startup class is now much cleaner:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(new App("switching-api"));
services.RegisterDbModule(SqlServerConnectionString);
}
Advantages should be clear at this point. We can use the RegisterDbModule
wherever we want. Multiple clients (and multiple Startup
classes) are not subject to change any more. If we need extra registrations in the DAL, we only need to change the extension method.
If you have a lot of layers, a lot of micro services, an N-Tier or message/event driven application; the RegisterDbModule
will not be enough.
Enter human readable registrations!
Moving on with the sample, we could split up the code even further:
public static IServiceCollection WithDbContext(this IServiceCollection services, string connectionString)
{
services.AddDbContext(
options => options.UseSqlServer(connectionString));
return services;
}
public static IServiceCollection WithFastReadReplica(this IServiceCollection services, string connectionString)
{
services.AddDbContext(
options => options.UseSqlServer(connectionString));
services.AddTransient();
return services;
}
public static IServiceCollection WithRepositories(this IServiceCollection services)
{
services.AddTransient();
return services;
}
Which then gives you more control regarding dependency availability for each client application. With the sample above, our Startup
class now looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(new App("switch-api"));
//no fast read service required for this client
services.WithDbContext(SqlServerConnectionString)
.WithRepositories();
}
Or, with the fast-read service required:
public void ConfigureServices(IServiceCollection services)
{
//fast read service required for this client
services.WithDbContext(SqlServerConnectionString)
.WithFastReadReplica(SqlServerConnectionString)
.WithRepositories();
}
This is, of course, an overly simplistic sample.
If you are working on a an application where the registrations get more complex, the advantages are enormous.
Let's take a look at a bootstrap Startup
class of a fairly complex application using Azure Service Bus, Azure BlobStorage and Azure functions:
public class Startup : FunctionsStartup
public override void Configure(IFunctionsHostBuilder builder)
{
var config = new ConfigurationBuilder().AddEnvironmentVariables().Build();
var connectionStore = new AzureCredentialStore(config);
builder.Services.AddSingleton(new App("some-app"));
builder.Services
.PerformDefaultRegistrationForFunction(connectionStore)
.WithAzureBlobStorage(typeof(AzureBlobContainer).Assembly)
.WithDbContext(connectionStore)
.WithRectificationTraceService()
.WithRetryHandling()
.WithEventModule()
.WithEntityCollectors()
.WithMarketExport();
builder.Services.AddLogging();
}
}
As you can see, the code is very clear and transparent. It only takes a second to analyze what will be available for this client during its run-time.
Hope you enjoyed the read and happy coding!
Photo by Markus Spiske on Unsplash
Fill in the form below and we’ll get back to you as soon as possible.
Oops. You seem to have written your full name in invisible ink. Please enter it so we can read it. Oops. You seem to have written your company in invisible ink. Please enter it so we can read it. It seems your e-mail doesn’t exist. Please enter a real one so we can contact you. Oops. You seem to have written your telephone in invisible ink. Please enter it so we can read it. Sorry, we could not send the enquiry.