【发布时间】:2011-11-09 11:19:49
【问题描述】:
如何使用设置(ApplicationSettingsBase)和依赖注入将所有配置文件代码排除在我的逻辑代码之外?
配置是指客户特定的配置文件。
我真的必须在每次需要时都注入一个配置类,还是有其他模式?
如果能得到一些示例代码就太好了!
样品:
静态配置:
public static class StaticConfiguration
{
public static bool ShouldApplySpecialLogic { get; set; }
public static string SupportedFileMask { get; set; }
}
public class ConsumerOfStaticConfiguration
{
public void Process()
{
if (StaticConfiguration.ShouldApplySpecialLogic)
{
var strings = StaticConfiguration.SupportedFileMask.Split(',');
foreach (var @string in strings)
{
}
}
}
}
非静态配置:
public interface IConfiguration
{
bool ShouldApplySpecialLogic { get; set; }
string SupportedFileMask { get; set; }
}
public class Configuration : IConfiguration
{
public bool ShouldApplySpecialLogic { get; set; }
public string SupportedFileMask { get; set; }
}
public class Consumer
{
private readonly IConfiguration _configuration;
public Consumer(IConfiguration configuration)
{
_configuration = configuration;
}
public void Process()
{
if (_configuration.ShouldApplySpecialLogic)
{
var strings = _configuration.SupportedFileMask.Split(',');
foreach (var @string in strings)
{
}
}
}
}
具有非静态配置的静态上下文:
public static class Context
{
public static IConfiguration Configuration { get; set; }
}
public class ConsumerOfStaticContext
{
public void Process()
{
if (Context.Configuration.ShouldApplySpecialLogic)
{
var strings = Context.Configuration.SupportedFileMask.Split(',');
foreach (var @string in strings)
{
}
}
}
}
【问题讨论】:
-
你想要的是一个控制反转容器
-
@Nico 我想要得到的是关于使用控制容器的反转将逻辑代码与配置分离的解释。
-
我写了一篇博文,解释了我们如何以及为什么使用 StructureMap 将我们的配置与我们的逻辑分开:lostechies.com/joshuaflanagan/2009/07/13/… 该博文中描述的功能现在可以在 FubuCore 实用程序库中使用(你可以得到它通过nuget):github.com/DarthFubuMVC/fubucore/tree/master/src/FubuCore/…
标签: c# configuration dependency-injection structuremap application-settings