我目前正在将IConfigFileSettings的具体ConfigFileSettings注入需要连接字符串名称的类中。简化代码如下:
public interface IConfigFileSettings
{
string GetConnectionString(string name);
}
public class ConfigFileSettings : IConfigFileSettings
{
public string GetConnectionString(string name)
{
return ConfigurationManager.ConnectionStrings[name].Name;
}
}
这适用于在iis,Windows服务和控制台应用程序中托管的webapi。我想:
ConfigurationManager.ConnectionStrings[name].Name
不适用于工作人员角色。我是否可以调整GetConnectionString方法以使其在所有环境中透明地工作?即使我得到连接sting名称(例如来自.cscfg文件),我的代码也会查找:
<connectionStrings> ... </connectionStrings>
我想我不能只在.cscfg文件中添加一个条目?
答案 0 :(得分:1)
您可以将它们放在.cscfg文件中,如:
<?xml version="1.0"?>
<ServiceConfiguration serviceName="Web.Azure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="3" osVersion="*" schemaVersion="2013-03.2.0">
<Role name="Worker">
<Instances count="2" />
<ConfigurationSettings>
<Setting name="connectionstringname" value="connectionstringvalue" />
</ConfigurationSettings>
</Role>
</ServiceConfiguration>
然后你可以通过以下方式阅读:
var connectionstring = RoleEnvironment.GetConfigurationSettingValue("connectionstringname");
答案 1 :(得分:1)
Castle Windsor DictionaryAdapter。我在我的项目中使用它。用法:
像在MyWorkerService.cs中一样注入您的配置
使用Configuration.Interfaces; 使用Persistence.Interfaces; 使用Worker.Services.Interfaces;
命名空间Worker.Services { 公共类MyWorkerService:IMyWorkerService { private readonly IConnectionStrings _connectionStrings; private readonly IAzureServiceConfiguration _azureServiceConfiguration; 私人只读IMicrosoftStorageConfig _microsoftStorageConfig; private readonly IPersitenceServiceConfigDependent _persitenceServiceConfigDependent; private readonly IAppConfigSettings _appConfigSettings;
public MyWorkerService(
IPersitenceServiceConfigDependent persitenceServiceConfigDependent,
IConnectionStrings connectionStrings,
IAzureServiceConfiguration azureServiceConfiguration,
IMicrosoftStorageConfig microsoftStorageConfig,
IAppConfigSettings appConfigSettings)
{
_connectionStrings = connectionStrings;
_azureServiceConfiguration = azureServiceConfiguration;
_microsoftStorageConfig = microsoftStorageConfig;
_persitenceServiceConfigDependent = persitenceServiceConfigDependent;
_appConfigSettings = appConfigSettings;
}
public string DoWork()
{
_persitenceServiceConfigDependent.ConfigDependentAction("blah");
var configSetting = _microsoftStorageConfig.StorageConnectionString;
return $"Job done :" +
$" <br> msConfig : {configSetting}, " +
$" <br> azureConfig.ServiceBusConnectionString:{_azureServiceConfiguration.ServiceBusConnectionString} " +
$" <br> webConfig.SubscriptionId:{_appConfigSettings.SubscriptionId} " +
$" <br> connectionStrings.DefaultConnection :{_connectionStrings.DefaultConnection}";
}
} }