IoC vs global variable in library

久未见 提交于 2019-12-08 09:10:52

问题


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?


回答1:


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.




回答2:


Use a container, that's the point in them. I've only used StructureMap but I can definitely recommend it. Loads of docs, and its really easy to get up and running with. Once youre comfortable with working with it you'll love how easy it makes things. Decoupling for the win!

In reality, your container will be a static class that you query for objects, so there sort of isnt really a choice :)



来源:https://stackoverflow.com/questions/947378/ioc-vs-global-variable-in-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!