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

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

问题描述

Microsoft的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配置很脆弱和详细


  • 在重命名类型或程序集时,配置会崩溃。

  • 您必须手动将相应的.dll文件复制到输出目录(或者使用构建脚本)。

  • 整体冗长,

作为一个经验法则,优选代码作为配置。但是,您可以将代码配置与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天全站免登陆