简体   繁体   English

如何在C#WebApi中将依赖项注入静态框架类中

[英]How to inject a dependency into a static framework class in C# WebApi

In my WebApiConfig.cs class for a .NET 4.6.1 WebApi project, I want to enable CORS only if an app setting in web.config is set to true. 在我的.NET 4.6.1 WebApi项目的WebApiConfig.cs类中,仅当web.config中的应用程序设置设置为true时,我才想启用CORS。 I generally read web.config AppSettings using an AppSettings class that converts the values from string to a more appropriate data type. 我通常使用AppSettings类读取web.config AppSettings,该类将值从字符串转换为更合适的数据类型。 I declare an IAppSettings interface and register the type with the Autofac DI container I'm using. 我声明一个IAppSettings接口,并将类型注册到我正在使用的Autofac DI容器中。

However, in this case, WebApiConfig is a static class, and its Register method is called as follows: GlobalConfiguration.Configure(WebApiConfig.Register); 但是,在这种情况下,WebApiConfig是静态类,其Register方法的调用方式如下:GlobalConfiguration.Configure(WebApiConfig.Register); I can't change the signature of the GlobalConfiguration.Configure class, so I don't see how to inject the IAppSettings object to make it accessible in the Register method. 我无法更改GlobalConfiguration.Configure类的签名,因此我看不到如何注入IAppSettings对象以使其在Register方法中可访问。 Of course I can access ConfigurationManager, but that seems very hacky. 当然,我可以访问ConfigurationManager,但这似乎很麻烦。 Of course I could also declare AppSettings as a static class, but that would make unit testing difficult. 当然,我也可以将AppSettings声明为静态类,但这会使单元测试变得困难。 Is there some cleaner way to do this? 有没有更清洁的方法可以做到这一点?

Here's the relevant code - the ConfigurationManager line is the one I want to replace with a call to an appSettings class: 这是相关的代码-ConfigurationManager行是我要替换为对appSettings类的调用的行:

    public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        if (System.Configuration.ConfigurationManager.AppSettings.Get("IsCorsEnabled", false))
        {
            config.EnableCors();
        }
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Many thanks for any assistance!! 非常感谢您的协助!

Say you have an interface like this for your appsettings (sort of): 假设您有一个这样的界面用于您的应用程序设置(多种):

public interface IAppSettings
{
    T Get<T>(string name);
}

And a default implementation of this which just wraps around ConfigurationManager : 这是默认的实现,它只是围绕ConfigurationManager

public class DefaultAppSettings : IAppSettings
{
    public T Get<T>(string name)
    {
        return (T)Convert.ChangeType(ConfigurationManager.AppSettings[name], typeof(T));
    }
}

If you then define a class like this: 如果然后定义这样的类:

public static class CurrentAppSettings
{
    public static Func<IAppSettings> Instance = () => new DefaultAppSettings();
}

You could use this in your register method: 您可以在注册方法中使用此方法:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        if (CurrentAppSettings.Instance().Get<bool>("IsCorsEnabled"))
        {
            config.EnableCors();
        }
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

If you want to inject some other implementation of this, like in a test, you just set the CurrentAppSettings instance to something else: 如果要注入其他实现,例如在测试中,只需将CurrentAppSettings实例设置为其他值即可:

[Test]
public void SomeTest()
{
    CurrentAppSettings.Instance = () => new SimpleKeyValueAppSettings(new Dictionary<string, string>());

    // ...
}

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

相关问题 如何使用ninject注入对WebAPI自定义处理程序的依赖 - c# How to Inject dependency on a custom handler for WebAPI using ninject 如何将依赖项注入到 static class - How to inject dependency to static class c#ninject实例化类中的注入依赖 - c# ninject inject dependency in a instantiated class C#依赖注入 - 如何在没有源的情况下注入依赖项? - C# dependency injection - how to you inject a dependency without source? 如何使用 Microsoft.Extensions.DependencyInjection 在 .net 框架中的 webapi 中注入依赖项? - How do I inject dependency in webapi in .net framework using Microsoft.Extensions.DependencyInjection? C# - 如何将新的依赖实例注入到在应用程序生命周期中实例化一次的 class? - C# - How to inject new instance of dependency to a class which get instantiated once in the app lifetime? 如何从单个类中的静态运行非静态方法并使用依赖注入 C# - How to run non static method from static inside single class and use dependency injection C# 如何在C#中注入一个类(不是接口)? - How to inject a class (not an interface) in C#? 如何在C#IComparer类中注入存储库? - How to inject repository in a C# IComparer class? 如何在 c# 中注入依赖注入期间定义的服务 - How to inject the service defined during the dependency injection in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM