如何为DI / IOC订购我的ctor参数? [英] How should I order my ctor parameters for DI/IOC?

查看:67
本文介绍了如何为DI / IOC订购我的ctor参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点像DI新手,所以请原谅我这是一个错误的方法还是一个愚蠢的问题。

I'm a bit of a DI newbie, so forgive me if this is the wrong approach or a silly question.

假设我有一个表单可以创建/更新订单,我知道它将需要检索要显示的产品和客户的列表。我想传递正在编辑的Order对象,但我也想将ProductsService和CustomersService注入为依赖项。

Let's say I have a form which creates/updates an order, and I know it's going to need to retrieve a list of products and customers to display. I want to pass in the Order object that it's editing, but I also want to inject the ProductsService and CustomersService as dependencies.

因此,我希望我的IoC容器(随身携带的其中一个容器)提供服务,但这取决于调用代码来提供Order对象。编辑。

So I will want my IoC container (whichever one I go with) to supply the services, but it'll be up to the calling code to supply the Order object to edit.

我应该将构造函数声明为将Order对象作为第一个参数,然后将ProductsService和CustomersService用作示例,例如:

Should I declare the constructor as taking the Order object as the first parameter and the ProductsService and CustomersService after that, eg:

public OrderForm(Order order, ProductsService prodsSvc, CustomersService custsSvc)

...或者应该首先依赖项,最后是Order对象,例如:

... or should the dependencies come first and the Order object last, eg:

public OrderForm(ProductsService prodsSvc, CustomersService custsSvc, Order order)

这有关系吗?是否取决于我使用的IoC容器?还是有更好的方式?

Does it matter? Does it depend on which IoC container I use? Or is there a "better" way?

推荐答案

我不同意@aku的回答。

I disagree with @aku's answer.

我认为您正在做的事还不错,还有其他做事的方法或多或少都是正确的。例如,人们可能会质疑此对象是否首先应该依赖于服务。

I think what you're doing is fine and there are also other ways to do it that are no more or less right. For instance, one may question whether this object should be depending on services in the first place.

无论使用哪种DI,我认为在您的脑海中至少阐明每个对象所处的状态是有帮助的,例如真实状态(顺序),派生状态(如果有)和依赖项(服务):

Regardless of DI, I feel it is helpful to clarify in your mind at least the kind of state each object holds, such as the real state (Order), derived state (if any), and dependencies (services):

http://tech.puredanger.com/2007/09/18/spelunking/

在任何构造函数或方法上,我更喜欢先传递真实数据,然后再传递依赖项或外部内容。因此,在您的示例中,我希望使用第一个。

On any constructor or method, I prefer the real data to be passed first and dependencies or external stuff to be passed last. So in your example I'd prefer the first.

这篇关于如何为DI / IOC订购我的ctor参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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