Use dependency injection in static class

丶灬走出姿态 提交于 2020-06-08 04:52:07

问题


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:


You basically have two options:

  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.

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

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

        return xxx; //xxxxx
    }
}

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

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.



来源:https://stackoverflow.com/questions/55213803/use-dependency-injection-in-static-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!