繁体   English   中英

在静态类中使用依赖注入

[英]Use dependency injection in static class

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

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

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

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;
    }
}

你基本上有两个选择:

  1. 将类从static更改为实例类,并通过构造函数注入提供依赖项。
  2. 通过Method Injection提供对类的公共方法的依赖。

以下是每个选项的示例。

选项 1. 将类从静态更改为实例类

将类从static更改为实例类,并通过Constructor Injection提供IConfiguracion 在这种情况下, XHelper应该被注入到其消费者的构造函数中。 例子:

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;

        return xxx;
    }
}

2. 通过方法注入将IConfiguration提供给Execute方法。

例子:

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;
    }
}

不太有利的选择

当然还有更多选项需要考虑,但我认为它们都不那么有利,因为它们要么会导致代码异味反模式

例如,您可能倾向于使用服务定位器,但这是一种反模式 环境背景; 同样的事情 另一方面, Property Injection会导致Temporal Coupling ,这是一种代码异味。

我遇到了这个问题,我开发了这个 nuget 包: ServiceCollectionAccessorService

repo: ServiceCollectionAccessorService它基本上是一个静态类,可以访问根服务集合,您可以从中构建您的提供者:

private static LogData GetLogData() => ServiceCollectionAccessor.Services.BuildServiceProvider().GetRequiredService<LogData>();

这个包在我的工作中是可操作的,我们没有任何问题。 我也没有问题解决范围服务。 我希望这可以帮助任何有同样问题的人。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM