Unity 应该在代码还是配置文件中配置? [英] Should Unity be configured in code or configuration file?

查看:31
本文介绍了Unity 应该在代码还是配置文件中配置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

微软的 Unity 依赖注入框架可以通过代码或应用程序配置文件 (app.config) 进行配置.

Microsoft's Unity dependency injection framework can be configured either through code or through the applications configuration file (app.config).

代码示例:

IUnityContainer container = new UnityContainer()
    .RegisterType<IInterface, ConcreteImplementation>();

配置示例:

<unity>
    <containers>
        <container>
            <types>
                <type type="IInterface, MyAssembly"
                      mapTo="ConcreteImplementation, MyAssembly" />

每种方法的优点/缺点是什么?我可以想到用户可以轻松配置您的应用程序"的明显优势,以及用户可以轻松破坏您的应用程序"的明显劣势,但还有什么不那么明显的吗?

What are the advantages/disadvantages to each approach? I can think of the obvious advantage "Users can easily configure your application", and the obvious disadvantage "Users can easily break your application", but is there anything less obvious?

推荐答案

XML 配置实际上只对一件事情有益:后期绑定.通过 XML 配置,您可以更改应用程序的组成方式,而无需重新编译整个应用程序.这对于支持一定程度用户配置的 ISV 应用程序尤其重要.ISV 可以发布带有默认行为的已编译应用程序,但允许客户/用户通过更改配置来更改部分行为.

XML configuration is really only beneficial for a single thing: Late Binding. With XML configuration you can change how your application is composed without recompiling the entire application. This is particularly relevant for ISV applications that support a degree of user configuration. ISVs can ship a compiled application with default behavior, but enable customers/users to change parts of the behavior by changing the configuration.

然而,XML 配置既脆弱又冗长.从开发者的角度来看,这只是一种痛苦的工作.

However, XML configuration is brittle and verbose. From a developer's viewpoint, it's just a pain to work with.

  • 重命名类型或程序集时,配置往往会中断.
  • 您必须手动将相应的 .dll 复制到输出目录(或让构建脚本执行此操作).
  • 整体冗长,难以使用.
  • 工具支持弱于强类型代码.

根据经验,首选代码作为配置.但是,您可以将 Code as Configuration 与 XML 配置进行匹配,因此如果您有一些需要后期绑定的依赖项,您可以使用 XML 配置.

As a rule of thumb, prefer Code as Configuration. However, you can match Code as Configuration with XML configuration, so if you have a few dependencies which should be late bound, you can use XML configuration for those.

这篇关于Unity 应该在代码还是配置文件中配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆