在.NET Core中的静态类中使用依赖注入

问题描述 投票:0回答:1

我需要在静态类中使用依赖注入。

静态类中的方法需要注入依赖项的值。

以下代码示例演示了我的问题:

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;
    }
}
c# class dependency-injection static
1个回答
3
投票

你基本上有两个选择:

  1. 将类从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 } }
  2. 通过IConfiguracionExecute提供给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,这是一种代码气味。

© www.soinside.com 2019 - 2024. All rights reserved.