处理可选依赖关系(C#)

前端之家收集整理的这篇文章主要介绍了处理可选依赖关系(C#)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们有一个应用程序可选地与TFS集成,但是由于集成是可选的,我显然不希望所有机器都需要TFS组件作为要求.

我该怎么办?

>我可以在我的主程序集中引用TFS库,并确保在使用TFS集成时,我仅引用TFS相关的对象.
>或者,更安全的选项是在一些单独的“TFSWrapper”程序集中引用TFS库:

一个.是否可以直接引用该程序集(只要我注意到我所说的话)

湾我是否应该为我的TFSWrapper程序集暴露一组接口来实现,然后在需要时使用反射实例化这些对象.

对我来说似乎有风险,在另一方面,2b似乎超过了顶级 – 我本来将构建一个插件系统.

当然必须有一个更简单的方法.

最安全的方法(即在应用程序中不会出错的最简单方法)可能如下.

制作一个可以吸引您使用TFS的界面,例如:

  1. interface ITfs
  2. {
  3. bool checkout(string filename);
  4. }

编写一个使用TFS实现此接口的类:

  1. class Tfs : ITfs
  2. {
  3. public bool checkout(string filename)
  4. {
  5. ... code here which uses the TFS assembly ...
  6. }
  7. }

编写另一个实现此接口的类,而不使用TFS:

  1. class NoTfs : ITfs
  2. {
  3. public bool checkout(string filename)
  4. {
  5. //TFS not installed so checking out is impossible
  6. return false;
  7. }
  8. }

在某个地方有一个单身人士

  1. static class TfsFactory
  2. {
  3. public static ITfs instance;
  4.  
  5. static TfsFactory()
  6. {
  7. ... code here to set the instance
  8. either to an instance of the Tfs class
  9. or to an instance of the NoTfs class ...
  10. }
  11. }

现在只有一个需要小心的地方(即TfsFactory构造函数);您的代码的其余部分可以调用TfsFactory.instance的ITfs方法,而不必知道是否安装了TFS.

要回答下面最近的评论

根据我的测试(我不知道这是否是“定义的行为”)抛出一个异常(一旦你调用一个取决于缺少的程序集的方法).因此,在程序集中的至少一个单独的方法(或一个单独的类)中将代码封装在代码上是非常重要的.

例如,如果Talk组件丢失,则不会加载以下内容

  1. using System;
  2. using OptionalLibrary;
  3.  
  4. namespace TestReferences
  5. {
  6. class MainClass
  7. {
  8. public static void Main(string[] args)
  9. {
  10. if (args.Length > 0 && args[0] == "1") {
  11. Talk talk = new Talk();
  12. Console.WriteLine(talk.sayHello() + " " + talk.sayWorld() + "!");
  13. } else {
  14. Console.WriteLine("2 Hello World!");
  15. }
  16. }
  17. }
  18. }

以下将加载:

  1. using System;
  2. using OptionalLibrary;
  3.  
  4. namespace TestReferences
  5. {
  6. class MainClass
  7. {
  8. public static void Main(string[] args)
  9. {
  10. if (args.Length > 0 && args[0] == "1") {
  11. foo();
  12. } else {
  13. Console.WriteLine("2 Hello World!");
  14. }
  15. }
  16.  
  17. static void foo()
  18. {
  19. Talk talk = new Talk();
  20. Console.WriteLine(talk.sayHello() + " " + talk.sayWorld() + "!");
  21. }
  22. }
  23. }

这些是测试结果(在Windows上使用MSVC#2010和.NET):

  1. C:\github\TestReferences\TestReferences\TestReferences\bin\Debug>TestReferences.exe
  2. 2 Hello World!
  3.  
  4. C:\github\TestReferences\TestReferences\TestReferences\bin\Debug>TestReferences.exe 1
  5.  
  6. 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.
  7. at TestReferences.MainClass.foo()
  8. at TestReferences.MainClass.Main(String[] args) in C:\github\TestReferences\TestReferences\TestReferences\Program.cs:
  9. line 11
  10.  
  11. C:\github\TestReferences\TestReferences\TestReferences\bin\Debug>

猜你在找的设计模式相关文章