.NET Core Dependency Injection with Func as constructor parameter

This post will be short and sweet, albeit one that caused me a bit of a headache. I recently worked on an ASP.NET Core project and I wanted to take advantage of the built-in Dependency Injection service to inject various services to the controllers. However, one of the services required a parameter in the constructor; to be more exact I was asked to create a unit of work for all the different zones that we have but the connection has to change for each region so this is the solution I came up with:
using Microsoft.Extensions.DependencyInjection;
string appConnection = "MyConnectionString";
string ConnectionStringProvider() => appConnection;
var services = new ServiceCollection();
services.AddTransient<IMyService>(s => new MyService(ConnectionStringProvider));
var provider = services.BuildServiceProvider();
var myService = provider.GetService<IMyService>();
Console.WriteLine($"The constructor parameter is: {myService?.ExecuteMyMostAwesomeSelectWithTheGivenConnection()}");
appConnection = "MyNewConnectionString1";
Console.WriteLine($"The constructor parameter is: {myService?.ExecuteMyMostAwesomeSelectWithTheGivenConnection()}");
Console.ReadKey();
public interface IMyService
{
string GetConstructorParameter();
}
public class MyService : IMyService
{
private readonly Func<string> _connectionString;
public MyService(Func<string> connectionStringProvider)
{
this._connectionString = connectionStringProvider;
}
public string ExecuteMyMostAwesomeSelectWithTheGivenConnection()
{
return _connectionString();
}
}
view raw Program.cs hosted with ❤ by GitHub

The important magick is here:
var myService = provider.GetService<IMyService>();
Console.WriteLine($"The constructor parameter is: {myService?.ExecuteMyMostAwesomeSelectWithTheGivenConnection()}");
appConnection = "MyNewConnectionString1";
Console.WriteLine($"The constructor parameter is: {myService?.ExecuteMyMostAwesomeSelectWithTheGivenConnection()}");
view raw Program.cs hosted with ❤ by GitHub

Comentarii

Postări populare de pe acest blog

RpiCar

Building Cross-Platform Desktop Apps with Electron.NET

NodeJS - Npm - set global node_modules