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

查看:120
本文介绍了我在使用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天全站免登陆