c# - 如何解耦 IoC 框架实现

标签 c# dependency-injection inversion-of-control unity-container enterprise-library

我一直在学习 IoC、依赖注入(inject)等,并且很享受这个过程。对我来说,接口(interface)解耦和编程的好处是显而易见的。

但是,我真的不喜欢将自己绑定(bind)到 Unity 或 Autofac 或 Windsor 等特定框架 - 因为我仍在学习并且尚未决定哪个最适合我的目的。

那么,我如何围绕 Unity 之类的东西进行包装,以便以后可以轻松地切换到 Windsor? (管他呢)。而且你敢说用另一个注入(inject)第一个 ;)

谢谢!

R.

附言我将 Unity 标记为我目前的个人偏好(我只是喜欢 Entlib)。

最佳答案

您当然可以通过使用 ResolveRegister 声明一个 IContainer 来尝试从容器中进行抽象。我这样做了几次。然后,您将继续实现一个 Container : IContainer 并用您的抽象封装一个实际的 IoC 容器。我用 Unity 和 CaSTLe Windsor 尝试过。

但是,嘿,很快我就意识到这真的是一种过度设计。然后我明白我试图从抽象中抽象出来,但又要建立另一个抽象。学习这个概念可能没问题,但在实际项目中这确实让人头疼。我强烈建议不要从 IoC 容器中抽象。如果您正确使用 DI 原则,无论如何更改您的容器将相当容易。

代码看起来过于复杂,比如

//I did this mess with Service Locator
var t = ContainerService.Instance.Resolve<IMyType>();
//others could go further with same Service Locator
var t = IoCFactory.Instance.CurrentContainer.Resolve<IMyType>();

//better way, use --> IoC and DI <--
//when a program starts, or a new instance of the context created
var t = Container.Resolve<IMyType>() //this lives at the bottom of the stack
//and then you just pass IMyType to the constructor of other types    
//you don't need to call Resolve again in the logical cycle

参见 this post由 Ayende 撰写。

Yes, they abstracted the Inversion of Control Container. I think that if you need to do that, it is pretty clear that you don’t really get what IoC is all about.

关于c# - 如何解耦 IoC 框架实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8750986/

相关文章:

c# - 如何在 C# 中创建一个以方法作为参数且参数数量不确定的方法?

c# - 在 .Net 中验证 Google Play 应用内支付签名 - 2048 位 key ,PKCS #1 v1.5

c# - 在 F# 记录上实现具有泛型参数的接口(interface)

c# - Unity 将异常包装到 ResolutionFailedException。如何避免?

c# - 在类库中初始化 IoC 容器的好策略是什么?

c# - 通过改变不同的构造函数类型来选择特定类型的结构图配置

c# - 禁用对位置服务 API 的访问

java - 如何绑定(bind) Activity 中 NavigationView 中的 TextView

javascript - AngularJS-错误 : Uncaught Error: [$injector:modulerr] http://

java - Guice 中的非目标绑定(bind)