使用 IoC 时我对接口抽象感到困惑 [英] I'm confused about interface abstractions when using IoC

查看:25
本文介绍了使用 IoC 时我对接口抽象感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在尝试学习 IoC,根据以下代码有几个问题:

I've recently been trying to learn IoC, and have a couple questions based on the following code:

public class WarriorModule : NinjectModule 
{
    public override void Load() 
    {
        Bind<IWeapon>().To<Sword>();
        Bind<Samurai>().ToSelf();
    }
}

我无法理解接口的新概念.在创建IRunnable 之类的接口之前,先实现函数void Run().使用 IoC,我现在将接口视为只映射到单个具体类的东西.假设,我如何将多个具体类映射到一个接口?我一直在读到你可以将多个接口映射到一个具体类,但不能反过来(除非这是上下文映射的地方)入戏).

I'm having trouble grasping the new concept of interfaces. Before I would create an interface such as IRunnable, implementing the function void Run(). With IoC, I'm now viewing an interface as something that only maps to a single concrete class. Assuming that, how would I map multiple concrete classes to an interface? I keep reading that you can map multiple interfaces to a single concrete class, but not the other way around (unless this is where contextual mapping comes into play).

假设接口只映射到单个对象,我什么时候应该创建一个接口而不是让一个对象绑定到自身?无论哪种方式,当映射时你都必须更改同一段代码更改正确吗?

Assuming interfaces only map to a single object, when should I create an interface as opposed to having an object bind to itself? Either way you will have to change the same piece of code when a mapping changes correct?

我标记了我所做的答案,因为它对我个人有帮助.不过,这两条评论都提供了同样的信息.

I marked the answer I did because it helped me personally. Both comments are equally informative though.

推荐答案

我最近从更一般的角度讨论了这个话题.最重要的是,松散耦合的代码倾向于产生过多的 1:1 接口.这违反了重用抽象原则.

I recently addressed this topic from a more general viewpoint. The bottom line is that there's a tendency for loosely coupled code to produce an overabundance of 1:1 interfaces. This is contrary to the Reused Abstractions Principle.

然而,这更像是一个应用程序设计问题,而不是关于特定 DI 容器的问题.虽然我不知道 Ninject,但我曾经使用过的所有其他容器(Castle Windsor、StructureMap、Spring.NET、Autofac、Unity 甚至 MEF)都可以将多个实现映射到同一个接口.他们如何做到这一点略有不同,但我在我的书的第四部分中介绍了所有这些内容 - 不幸的是,Ninject 没有包含在书中.

However, this is more of an application design issue than it's an issue regarding particular DI Containers. While I don't know Ninject, all other containers I've ever worked with (Castle Windsor, StructureMap, Spring.NET, Autofac, Unity, and even MEF) can map multiple implementations to the same interface. How they do this differ slightly, but I cover all of them in part IV of my book - unfortunately, Ninject is not covered in the book.

这篇关于使用 IoC 时我对接口抽象感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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