在MVC使用DI时,大规模的控制器构造函数参数列表 [英] Massive controller constructor argument list when using DI in MVC

查看:256
本文介绍了在MVC使用DI时,大规模的控制器构造函数参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用依赖注入autofac ASP.NET MVC3解决方案。
我们的控制器正在autofac和正确地创建和所有必需的对象在被正确传递,这些对象通常包括服务,仓库和映射器域对象转换为MVC(视图)模型。因此控制器构造颇像:

I am working on ASP.NET MVC3 solution that uses dependency injection with autofac. Our controllers are being created by autofac and properly and all required objects are being properly passed in. Those objects usually include services, repositories, and mappers converting domain object to MVC (view) models. So the controller constructor looks somewhat like:

public abcController(
        ILogger logger,
        IabcRepository abcRepository,
        IabcService abcService,
        IMapper<AbcDomain, AbcViewModel> abcMapper,
        ...
        )

不幸的是,假以时日,这些构造函数的参数列表往往相当迅速成长。我们的一些控制器目前预计60或多个参数。

Unfortunately, in time, those constructor parameter lists tend to grow quite quickly. Some of our controllers expect now 60 or more parameters.

难道我们在这里创造了一些反模式?

Did we create some anti-pattern here?

修改

我应该提到我们尝试按照薄位指示模式。也最这些参数往往是映射器 - 约66%。控制方法通常非常简单,要么遵循这个模式:

I should have mentioned that we try to follow thin contoller pattern. Also most of those parameters tend to be mappers - around 66%. The control methods are usually very simple, and follow either this pattern:


  • 基于参数调用相应的服务或资料库

  • 使用映射器结果转换为相应的视图模式

  • 通浏览模式,查看

或者这样的模式:


  • 从POST操作接收模式

  • 使用映射器将其转换为appropiate域对象

  • 调用相应的服务或存储库的域对象

推荐答案

60或多个参数是很多。

60 or more parameters is a lot.

在你的问题,你说..Those对象通常包括服务,仓库和映射器域对象转换为MVC(视图)模型......

In your question you stated "..Those objects usually include services, repositories, and mappers converting domain object to MVC (view) models..."

您已经有了一个肥胖控制器(不是托马斯任务引擎的那种),但它们已经做了太多的控制器。

You've got a Fat Controller (not the Thomas The Task Engine kind) but a controller that is doing too much.

平衡我寻找的是高脂模型瘦控制器。伊恩·库珀谈论它以及在此博客文章

The balance I look for is Fat Model skinny controller. Ian Cooper talks about it well in this blog post

您也可以看看的东西,如哪些参数实际上是跨扦插的担忧。

You can also look at things such as which parameters are actually cross cuttings concerns.

有关实例映射和日志记录在我的脑海里是横切关注点,所以你可能会使用操作过滤器来清理你的控制器。

For instance Mapping and Logging in my mind are cross cutting concerns so you could potentially use Action Filters to clean up your controllers.

这篇关于在MVC使用DI时,大规模的控制器构造函数参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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