在点网核心中注入强类型配置设置的问题

时间:2018-07-13 06:23:50

标签: asp.net-core .net-core asp.net-core-mvc asp.net-core-2.0 asp.net-core-webapi

我们有一个公共的类库项目,其中有一个名为say MyClass的类,该类实现了IMyClass。

public class MyClass : IMyClass
{       
    private readonly string _myConfigPath;     

    public TimeSheet(MyConfigPath myConfigPath)
    {            
        _myConfigPath= myConfigPath.Value;
    }
    public void GetData(int id)
    {
         var values= _myConfigPath;
    }
}
public interface IMyClass
{
    void GetData(int id);
}

我的类MyConfigPath是从ConfigInjector.ConfigurationSetting抽象调用扩展的。

public class MyConfigPath  : ConfigurationSetting<string>
{

}

在较旧的项目中,我们使用AutoFac通过ConfigInjector注入配置设置。

但是现在我们正在基于.Net Core2.1的新项目中,我们必须使用以MyClass编写的业务逻辑。

尽管我可以像这样在新项目的控制器中注入IMyClass类型

   services.ConfigurePOCO<MyConfigPath>(configuration.GetSection("AppSettings:MyConfigPath"));
 services.AddTransient<IMyClass , MyClass>();

但是分配给_myConfigPath的值仍然为空,因为我们没有为configinjector提供任何配置信息。

我试图遵循 StrathWeb BlogRick Strahl's Web Log 但是这些仅用于强类型对象,而不适用于configinjector。

我已经尝试过两种方式

 services.Configure<MyConfigPath >(configuration.GetSection("AppSettings:MyConfigPath "));

并创建StrathWeb Blog指定的扩展方法。

  services.ConfigurePOCO<MyConfigPath>(configuration.GetSection("AppSettings:MyConfigPath"));

更改类库项目的机会很少,因为许多其他项目不在.net核心上。 这是我的appsettings.json文件的方式

{
 "AppSettings": {
  "MyConfigPath": "C:\\EmployeeUpload"
  }
}

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

首先,如果您使用的是.Configure方法,则不会注入MyConfigPath,而是注入IOptions<MyConfigPath>(请再次关注第一个链接)。因此,您的注射变成这样:

public MyClass(IOptions<MyConfigPath> myConfigPathOptions)

第二,configuration.GetSection用于访问整个节,而不仅仅是字符串。如果要直接从JSON访问“ MyConfigPath”,则可以使用configuration["AppSettings:MyConfigPath"]。您可以像GetSection这样使用configuration.GetSection("AppSettings"),以整体获取所有应用程序设置。

我建议您查看IConfigurationIOptions的文档

我认为您真正想做的是这样的:

为您的所有设置创建一个班级:

public class MyAppSettings {
    public string MyConfigPath {get; set;} 
    public int MyOtherSetting { get; set; } // sample of how you could have more
}

上面添加了“ MyOtherSetting”的json看起来像这样:

{
    "AppSettings": {
        "MyConfigPath": "C:\\EmployeeUpload",
        "MyOtherSetting" : 501
    }
}

在启动类中,您可以使用以下代码:

services.Configure<MyAppSettings>(configuration.GetSection("AppSettings")

现在,对于注射,您将需要使用以下内容:

MyClass(IOptions<MyAppSettings> settingOptions)
{            
    _myConfigPath = myConfigPath.Value.MyConfigPath;
}

答案 1 :(得分:0)

我已经找到解决我所面临问题的方法。一点点使用反射在这里帮助了我。

下面是解决方法

var type= typeof(MyConfigPath);
var t = Activator.CreateInstance(type);
PropertyInfo propertyInfo = type.GetProperty("Value");
var configValue = configuration.GetValue<string>($"AppSettings:{type.Name}");
if (!string.IsNullOrEmpty(configValue) && propertyInfo != null)
{
  propertyInfo.SetValue(t, configValue, null);
}
services.AddSingleton(type, t);

通过这种方式,我能够注入我的强类型类。我之所以使用反射,是因为我必须对类库中的许多类型做同样的事情。

我通过一些研发和与团队的讨论获得了这个想法。

相关问题