IoC vs库中的全局变量 [英] IoC vs global variable in library

查看:146
本文介绍了IoC vs库中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public MyType(IComObject wrapper,字符串表){} 

现在IComObject是两个不同COM对象的封装。所有的(90%)我的类型都必须使用
IComObject,所以在DI模式下(为了测试),我将IComObject传递给需要它的每种类型。

主要的问题是,当有人去使用我的COM包装器库时,必须将IComObject的一个实例传递给它所做的所有事情,这使得代码有点难管理和维护。

我想知道是否应该使用IoC容器或用户可以设置的全局变量,以便它们不必传递IComOject实例。示例:

  public MyType(string table)
:this(IoC.Resolve< IComObject>,table){}

  public MyType(string table)
:this(StaticClass.ComInstance,table){}



$ p
$ b

  //设置Ioc容器
COMObject object = new COMObject();
Ioc.Register(typeof(IComObject),object);
MyType mytype = new MyType(test.tab);

  COMObject object = new COMObject(); 
StaticClass.ComInstance = object;
MyType mytype = new MyType(test.tab);

您认为我应该在这种情况下做什么?

IoC绝对是您的选择。 Globals不是编程中最糟糕的邪恶,少数全局并不是最糟糕的事情,但IoC是一个很好的,干净的模式,从长远来看,它是很好理解和易于维护的。 IoC的依赖性也更加明确。


So say that I have type that takes some parameters in the constructor, like this:

public MyType(IComObject wrapper,string table) {}

now IComObject is a wrapper over a two different COM objects. All(90%) of my types have to use IComObject, so in good DI fashion (to allow for testing) I am passing IComObject into every type that needs it.

The main problem is that when someone goes to use my COM wrapper library that have to pass an instance of IComObject into everything they do which makes the code a little bit hard to manage and maintain.

I was wondering if I should use a IoC container or a global variable that the user can set so that they don't have to pass the IComOject instance around. Example:

public MyType(string table)
       : this(IoC.Resolve<IComObject>,table) {}

or

public MyType(string table)
   : this(StaticClass.ComInstance,table) {}

So that the user can do this:

//Set up Ioc container
COMObject object = new COMObject();
Ioc.Register(typeof(IComObject),object);
MyType mytype = new MyType("test.tab");

or

COMObject object = new COMObject();
StaticClass.ComInstance = object;
MyType mytype = new MyType("test.tab");

What do you think I should do in this situation?

解决方案

IoC is definitely the way to go. Globals aren't the worst evil in programming, and a small number of globals aren't the worst thing, but IoC is a nice, clean pattern that is well understood and easier to maintain in the long run. Dependencies are also more explicit with IoC.

这篇关于IoC vs库中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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