我需要在静态类中使用依赖注入。
静态类中的方法需要注入依赖项的值。
以下代码示例演示了我的问题:
public static class XHelper
{
public static TResponse Execute(string metodo, TRequest request)
{
// How do I retrieve the IConfiguracion dependency here?
IConfiguracion x = ...;
// The dependency gives access to the value I need
string y = x.apiUrl;
return xxx;
}
}
你基本上有两个选择:
static
更改为实例类,并通过IConfiguracion
提供Constructor Injection。在这种情况下,XHelper
应注入其消费者的构造者。例:
public class XHelper
{
private readonly IConfiguracion config;
public XHelper(IConfiguracion config)
{
this.config = config ?? throw new ArgumentNullException(nameof(config));
}
public TResponse Execute(string metodo, TRequest request)
{
string y = this.config.apiUrl; //i need it
return xxx; //xxxxx
}
}
IConfiguracion
将Execute
提供给Method Injection方法。例:
public static class XHelper
{
public static TResponse Execute(
string metodo, TRequest request, IConfiguracion config)
{
if (config is null) throw new ArgumentNullException(nameof(config));
string y = config.apiUrl;
return xxx;
}
}
所有其他选项都不在桌面上,因为它们会导致代码异味或反模式。例如,您可能倾向于使用服务定位器模式,但这是一个坏主意,因为那是an anti-pattern。另一方面,Property Injection导致Temporal Coupling,这是一种代码气味。