在静态类中使用依赖注入 [英] Use dependency injection in static class

查看:1092
本文介绍了在静态类中使用依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to use Dependency Injection in a static class.

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

the method in the static class needs the value of an injected dependency.

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

The following code sample demonstrates my problem:

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 更改为实例类,然后通过构造函数注入供应 IConfiguracion

  2. 通过Execute 方法提供 IConfiguracion 。 bz / jONp rel = noreferrer>方法注入。

  1. Change the class from static to an instance class and supply IConfiguracion through Constructor Injection.
  2. Supply the IConfiguracion to the Execute method through Method Injection.

以下是每个选项的示例。

Here are examples for each option.

将类从更改为静态到实例类,并通过构造函数提供 IConfiguracion 注射。在这种情况下,应将 XHelper 注入其使用者的构造函数中。示例:

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(nameof(config));
    }

    public TResponse Execute(string metodo, TRequest request)
    {
        string y = this.config.apiUrl;  //i need it

        return xxx; //xxxxx
    }
}



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



示例:

2. Supply the IConfiguracion to the Execute method through Method Injection.

Example:

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

所有其他选项均已取消,因为它们会引起代码异味或反模式。例如,您可能倾向于使用Service Locator模式,但这不是一个好主意,因为它是一个反模式 。另一方面,属性注入会导致临时耦合,这是一个代码气味。

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 the Service Locator pattern, but that's a bad idea because that's an anti-pattern. Property Injection, on the other hand, causes Temporal Coupling, which is a code smell.

这篇关于在静态类中使用依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆