Dependency injection duplication in Controller and BaseController in .Net Core 2.0

前端 未结 3 1025
太阳男子
太阳男子 2021-02-01 21:54

If I create a BaseController in my Asp.Net Core 2.0 web application that capsulizes some of the common dependencies are they still necessary in the actual controllers.

F

3条回答
  •  无人共我
    2021-02-01 22:28

    There are very few good reasons to use a BaseController in MVC. A base controller in this scenario only adds more code to maintain, with no real benefit.

    For true cross-cutting concerns, the most common way to handle them in MVC is to use global filters, although there are a few new options worth considering in MVC core.

    However, your problem doesn't look like a cross-cutting concern so much as a violation of the Single Responsibility Principle. That is, having more than 3 injected dependencies is a code smell that your controller is doing too much. The most practical solution would be to Refactor to Aggregate Services.

    In this case, I would argue that you have at least 1 implicit service that you need to make explicit - namely, UserManager and SignInManager should be wrapped into a service of its own. From there, you could potentially inject your other 3 dependencies into that service (depending on how they are used, of course). So, you could potentially whittle this down to a single dependency for both the AccountController and ManageController.

    Some signs that a controller is doing too much:

    1. There are a lot of "helper" methods that contain business logic that are shared between actions.
    2. Action methods are doing more than simple HTTP request/response stuff. An action method should generally do nothing but call services that process input and/or produce output and return views and response codes.

    In cases such as these, it is worth a look to see if you can move that logic into a service of their own and any shared logic into dependencies of that service, etc.

提交回复
热议问题