gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:12:09 27 4
gpt4 key购买 nike

我一直在学习 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com