.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:
The important magick is here:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
The important magick is here:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var myService = provider.GetService<IMyService>(); | |
Console.WriteLine($"The constructor parameter is: {myService?.ExecuteMyMostAwesomeSelectWithTheGivenConnection()}"); | |
appConnection = "MyNewConnectionString1"; | |
Console.WriteLine($"The constructor parameter is: {myService?.ExecuteMyMostAwesomeSelectWithTheGivenConnection()}"); |
Comentarii