我们有一个应用程序可选地与TFS集成,但是由于集成是可选的,我显然不希望所有机器都需要TFS组件作为要求.
我该怎么办?
>我可以在我的主程序集中引用TFS库,并确保在使用TFS集成时,我仅引用TFS相关的对象.
>或者,更安全的选项是在一些单独的“TFSWrapper”程序集中引用TFS库:
一个.是否可以直接引用该程序集(只要我注意到我所说的话)
湾我是否应该为我的TFSWrapper程序集暴露一组接口来实现,然后在需要时使用反射实例化这些对象.
对我来说似乎有风险,在另一方面,2b似乎超过了顶级 – 我本来将构建一个插件系统.
当然必须有一个更简单的方法.
最安全的方法(即在应用程序中不会出错的最简单方法)可能如下.
制作一个可以吸引您使用TFS的界面,例如:
- interface ITfs
- {
- bool checkout(string filename);
- }
编写一个使用TFS实现此接口的类:
- class Tfs : ITfs
- {
- public bool checkout(string filename)
- {
- ... code here which uses the TFS assembly ...
- }
- }
编写另一个实现此接口的类,而不使用TFS:
- class NoTfs : ITfs
- {
- public bool checkout(string filename)
- {
- //TFS not installed so checking out is impossible
- return false;
- }
- }
在某个地方有一个单身人士
- static class TfsFactory
- {
- public static ITfs instance;
- static TfsFactory()
- {
- ... code here to set the instance
- either to an instance of the Tfs class
- or to an instance of the NoTfs class ...
- }
- }
现在只有一个需要小心的地方(即TfsFactory构造函数);您的代码的其余部分可以调用TfsFactory.instance的ITfs方法,而不必知道是否安装了TFS.
要回答下面最近的评论:
根据我的测试(我不知道这是否是“定义的行为”)抛出一个异常(一旦你调用一个取决于缺少的程序集的方法).因此,在程序集中的至少一个单独的方法(或一个单独的类)中将代码封装在代码上是非常重要的.
例如,如果Talk组件丢失,则不会加载以下内容:
- using System;
- using OptionalLibrary;
- namespace TestReferences
- {
- class MainClass
- {
- public static void Main(string[] args)
- {
- if (args.Length > 0 && args[0] == "1") {
- Talk talk = new Talk();
- Console.WriteLine(talk.sayHello() + " " + talk.sayWorld() + "!");
- } else {
- Console.WriteLine("2 Hello World!");
- }
- }
- }
- }
以下将加载:
- using System;
- using OptionalLibrary;
- namespace TestReferences
- {
- class MainClass
- {
- public static void Main(string[] args)
- {
- if (args.Length > 0 && args[0] == "1") {
- foo();
- } else {
- Console.WriteLine("2 Hello World!");
- }
- }
- static void foo()
- {
- Talk talk = new Talk();
- Console.WriteLine(talk.sayHello() + " " + talk.sayWorld() + "!");
- }
- }
- }
这些是测试结果(在Windows上使用MSVC#2010和.NET):
- C:\github\TestReferences\TestReferences\TestReferences\bin\Debug>TestReferences.exe
- 2 Hello World!
- C:\github\TestReferences\TestReferences\TestReferences\bin\Debug>TestReferences.exe 1
- Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'OptionalLibrary,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
- at TestReferences.MainClass.foo()
- at TestReferences.MainClass.Main(String[] args) in C:\github\TestReferences\TestReferences\TestReferences\Program.cs:
- line 11
- C:\github\TestReferences\TestReferences\TestReferences\bin\Debug>