Dependency Inversion Principle and where to put the interfaces

半世苍凉 提交于 2019-12-06 07:10:44

问题


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.

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)
    {

     ...

    }

The structured of the files is this one:

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.

Thanks, Asier


回答1:


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.



来源:https://stackoverflow.com/questions/14057968/dependency-inversion-principle-and-where-to-put-the-interfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!