这里更大的问题是在appSettings 中存储值列表并非易事。 This question addresses it 最好的答案是在设置文件中创建自己的部分,然后您必须通过 ConfigurationManager.GetSection() 而不是 ConfigurationManager.AppSettings.Get()、which is what Dependency.OnAppSettingsValue() uses 访问该部分。查看Dependency 类的其余部分,似乎没有内置方法可以做到这一点。
但是,如果它真的只是您需要的字符串,那么您至少有两个还不错的选项(在我看来)。
1.使用 StringCollection 将字符串存储在 App.config 文件中。
这只是在 App.config 中创建您自己的部分的更短的内置版本。使用 Visual Studio 的项目属性页面中的编辑器添加类型为 StringCollection 的应用程序设置。这将使您的 App.config 看起来像这样:
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="YourApplication.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<YourApplication.Properties.Settings>
<setting name="SomeStrings" serializeAs="Xml">
<value>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>one</string>
<string>two</string>
<string>three</string>
</ArrayOfString>
</value>
</setting>
</YourApplication.Properties.Settings>
</applicationSettings>
</configuration>
然后在配置你的组件时:
// StringCollection only implements IList, so cast, then convert
var someStrings = Properties.Settings.Default.SomeStrings.Cast<string>().ToArray();
container.Register(Component.For<IMyComponent>()
.ImplementedBy<MyComponent>()
.LifestyleTransient()
.DependsOn(Dependency.OnValue<IList<string>>(someStrings)));
2。将字符串作为分隔列表存储在appSettings 中,然后手动拆分它们。
这可能是更简单的方法,但假设您可以找出字符串的分隔符(可能并非总是如此)。将值添加到您的 App.config 文件中:
<configuration>
<appSettings>
<add key="SomeStrings" value="one;two;three;four" />
</appSettings>
</configuration>
然后在配置你的组件时:
var someStrings = ConfigurationManager.AppSettings["SomeStrings"].Split(';');
container.Register(Component.For<IMyComponent>()
.ImplementedBy<MyComponent>()
.LifestyleTransient()
.DependsOn(Dependency.OnValue<IList<string>>(someStrings)));
在任何一种情况下,我们都只是在Dependency.OnValue 之上添加了少量工作,这就是Dependency.OnAppSettingsValue 所做的一切。
我认为这回答了你的问题,但要明确:
- 是的,但是您要自己进行转换,以便您可以转换成任何您想要的东西。
- 查看链接的问题和accepted answer,或使用
StringCollection。
-
Dependency.OnValue 是扩展名(在我看来),我不知道或看到任何其他地方你会这样做。但是,鉴于上述步骤,我认为没有必要这样做。