I've found the documentation on this topic very lacking and I'm in too much of a time squeeze to read a book on the topic. Is this a correct understanding of how to use Microsoft.Extensions.DependencyInjection
?
My understanding is that DI frameworks cut down boilerplate. Imagine you have 30 different classes that your need to dependency inject has convinced you all want a SqlConnection Conn
argument. You know that there's a sensible default SqlConnection
that you will want to use all of the time except when doing unit tests. Furthermore, imagine that all of these classes take genuine parameters in their constructors that have nothing to do with dependency injection (e.g. the first parameter in SqlClass1(string UserName, SqlConnection Conn)
or SqlClass2(string UserID, SqlConnectionConn)
). You could write an extra constructor for each of them that lets you leave the SqlConnection
unspecified and defaults to your sensible default, but this is way too much work. Instead, a DI framework lets you write code like this and put it in the same class as Main()
.
using Microsoft.Extensions.DependencyInjection;
static class Program
{
public static IServiceProvider ServiceProvider { get; private set; }
static IHostBuilder CreateHostBuilder()
{
return Host.CreateDefaultBuilder().ConfigureServices((context, services)=>{
// Tells callers to replace any requests for `SqlConnection` types with my sensible default.
services.AddTransient<SqlConnection, MySensibleDefaultSqlConnection()>();
// Tells callers that SqlClass1 is one of the callers that should replace its `SqlConnection`.
services.AddTransient<SqlClass1>();
// The same for SqlClass2.
services.AddTransient<SqlClass2>();
// [...]
services.AddTransient<SqlClass30>();
});
}
static void Main()
{
var host = CreateHostBuilder().Build();
ServiceProvider = host.Services;
// When we actually want to use one of the classes that use our sensible default, we do
var x = ServiceProvider.GetRequiredService<SqlClass1>("foo");
// rather than...
// var x = SqlClass1("foo", MySensibleDefaultSqlConnection());
}
}