2

We use an Ioc Container to resolve most of the objects in a project, however it seems like it might be innappropriate to use it everywhere. At runtime, the user is in the context of a single company Id and it seems appropriate to me to pass that company Id in the constructor of, for example, a repository or unit of work. We could use a parameter override for the company Id at runtime, but is there any benefit in using

var uow = IocContainer.Resolve<IUnitOfWork>(new ParameterOverride("companyId", companyId))

as opposed to

var uow = new UnitOfWork(companyId)

OK, so I understand that I might want to create a different implementation of IUnitOfWork some time and I could then easily swap in the new implementation with Ioc configuration, but I am not convinced I will ever do that anyway.

4

2 回答 2

4

不,有时呼叫new正是您想要的。一个示例是方法调用或狭窄范围的本地对象。

模型对象通常不受 IoC 容器的控制。您为每个新会话或请求范围实例化一个,使用从用户传递给您的数据,这些数据在启动时 IoC 容器永远无法知道。

更新:Honza Brestan 关于逻辑单元的观点是正确的。典型的 Spring 层排列是基于接口的:

view->controller->service->persistence

服务使用其他服务、模型对象和持久性来完成用例。

于 2012-12-18T12:28:50.140 回答
2

我发现 IoC 的最大优势不在于实现交换(在大多数项目中人们几乎不会这样做),而是迫使您将代码划分为更清晰的逻辑单元,这通常意味着它是可单元测试的、可管理的并且更容易整体原因。

考虑到这一点,我建议根据项目的逻辑单元为自己决定“注入粒度”。可能是 5 个较大的模块,也可能是几十个不同的小连接器。同样正如 duffymo 提到的,new可能是您想要的本地/狭窄范围。

于 2012-12-18T12:35:36.530 回答