应用程序设置界面
Reed Copsey 对以下 SO 问题做出了回应:
我更喜欢创建一个界面来设置查询、加载和 保存。通过使用依赖注入,我可以将其注入到每个 需要它的组件。
有人可以给出一个代码示例吗?例如,基于此“接口”(可以是 DI)的电子邮件客户端的设置类和 FTP 客户端的另一个设置类。我知道您可以为应用程序中的所有设置执行全局单例(我目前正在这样做),但里德的建议很有趣,并且想尝试一下。
Reed Copsey gave this response to the following SO Question:
Which design patterns can be applied to the configuration settings problem?
I prefer to create an interface for setting query, loading, and
saving. By using dependency injection, I can inject this into each
component that requires it.
Can someone give a code example of this? For instance a Settings class for an Email Client and another Settings class for a FTP Client based on this "interface" that can be DI. I understand that you can do a global singleton for all settings within the application (which I am currently doing) but this recommendations from Reed is interesting and would like to try it out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于接口,我会做这样的事情:
然后我会实现该接口一次,并使用 MEF 进行依赖项注入。我想我会用 LinqToXml 来实现它以加载/保存到 XML,并且可能有一个字典来缓存内存中的设置。另一种方法是对对象进行二进制序列化并将快照转储到某处(这有其缺点,例如它不可读)。
如果您只保存字符串和/或数字,XML 是一个不错的选择。如果您只有字符串,您甚至可以放弃泛型。
For the interface, I would do something like this:
Then I would implement that interface once and dependency inject it with let's say MEF. I guess I'd implement it with LinqToXml to load/save to XML and maybe have a Dictionary to cache the settings in memory. Another way would be to binary serialize your objects and dump a snapshot somewhere (which has it's downsides, e.g. it is not human-readable).
If you only save strings and/or numbers, XML is a good choice. If you only have strings, you can even ditch the generics.