You basically have two options:
- Change the class from
static
to an instance class and supply IConfiguration
through Constructor Injection.
- Supply the
IConfiguration
to the Execute
method through Method Injection.
Here are examples for each option.
Option 1. Change the class from static to an instance class
Change the class from static
to an instance class and supply IConfiguracion
through Constructor Injection. XHelper
should in that case be injected into the constructor of its consumers. Example:
public class XHelper
{
private readonly IConfiguration config;
public XHelper(IConfiguration config)
{
this.config = config ?? throw new ArgumentNullException("config");
}
public TResponse Execute(string metodo, TRequest request)
{
string y = this.config.apiUrl; //i need it
return xxx; //xxxxx
}
}
2. Supply the IConfiguration
to the Execute
method through Method Injection.
Example:
public static class XHelper
{
public static TResponse Execute(
string metodo, TRequest request, IConfiguration config)
{
if (config is null) throw new ArgumentNullException("config");
string y = config.apiUrl;
return xxx;
}
}
All other options are off the table because they would either cause code smells or anti-patterns. For instance, you might be inclined to use a Service Locator, but that's a bad idea because that's an anti-pattern. Ambient Context; same thing. Property Injection, on the other hand, causes Temporal Coupling, which is a code smell.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…