依赖倒置原则,哪里放置接口 [英] Dependency Inversion Principle and where to put the interfaces

查看:253
本文介绍了依赖倒置原则,哪里放置接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建在asp.net中一个简单的MVC应用程序。我想跟着依赖倒置原则,我不知道如果我这样做是正确的。

I am building a simple MVC application in asp.net. I want to follow the dependency inversion principle and I don't know if I am doing it right.

我目前工作的认证系统。我有一个使用内部的身份验证服务中的AccountController。该身份验证服务注入由构造函数注入控制器

I am currently working on the Authentication system. I have an AccountController which uses the Authenticator service inside. The Authenticator service is injected into the controller by constructor injection.

public class AccountController : Controller
{
    private IAuthenticator _authenticator;

    public AccountController(IAuthenticator authenticator)
    {
        _authenticator = authenticator;
    }

    //
    // POST: /Account/Login

    [HttpPost]
    public ActionResult Login(LoginModel model, string redirectToUrl = null)
    {

     ...

    }

结构化的文件是这个:

但我在想,如果我想要一个完全颠倒控制器及其依赖我会的礼仪移动下一个给控制器的认证服务的接口。事情是这样的:

But I was thinking that if I want a to fully inverted the decencies between the controller and its dependencies I will have to move the interface of the authentication service next to the controller. Something like this:

此方式,在客户端 - 控制器 - 和该服务的抽象将璧坐在相同的命名空间。所以在服务的接口的改变将来自客户机,将被传播到服务实现。代替前者方法,其中,在服务发生变化传播到客户端。依赖倒置 - 服务是依赖于客户端的

This way, the client - the controller - and the abstraction of the service will bi sitting in the same namespace. So changes in the interface of the service will come from the client and will be propagated to the service implementation. Instead of the former way, where changes happening in the service were propagated to the client. The dependency is Inverted - the service is dependent of the client.

我可以看到这样做的好处时,客户端和服务都在不同的组件,但我并不确定如果我应该做这个,当涉及到同一程序集。

I can see the benefit of this when client and service are in different assemblies, but I am not that sure if I should be doing this when it comes to the same assembly.

让和我知道,如果我这样做是否正确,我应该使用的第一个文件结构或第二之一。

Let me know if I am doing this right and whether I should use the first file structure or the second one.

谢谢,
Asier

Thanks, Asier

推荐答案

的代码文件的位置差别不大 - 这是一种组织你的源代码,无关的控制反转的问题。

The location of the code files makes little difference - this is a matter of organizing your source code, nothing to do with inversion of control.

重要的是,你是注射依赖到控制器,它给你。

What's important is that you are injecting the dependency into the controller, which you are.

这篇关于依赖倒置原则,哪里放置接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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