IoC 应该走多远?
我刚刚在一个非常小的项目中使用了 IoC,只需要测试一个对象。我现在开始将其实施到一个更大的现有项目中,但我不确定某些事情。
假设我有两个业务对象 Student
和 Teacher
都有一个名为 IUnitOfWork
的接口的构造函数注入,该接口具有 SQLUnitOfWork
的具体实例化代码>或<代码>InMemoryUnitOfWork。
因此,如果我使用这个库,我可以使用 IoC 来构造我的对象,不用担心,但是当我想在另一个库中使用一个库时会发生什么?假设我延迟加载属性 Student.Teacher
并且需要获取新的 Teacher
对象,我该怎么做?
使用 IoC 容器来实现这一点似乎不太正确,但使用具体对象也是如此。对每个使用的单个对象使用 IoC 似乎有点多余。
I've just used IoC on a very small project with only one object i needed to test. I'm now starting to implement it into a larger existing project and I'm unsure of something.
Say i have two business objects Student
and Teacher
both have constructor injection for an interface called IUnitOfWork
which has concrete instantiations of SQLUnitOfWork
or InMemoryUnitOfWork
.
So if i'm using this library I can use IoC to construct my object no worries, but what happens when I want to use one inside the other? So say I was lazy loading a property Student.Teacher
and need to get a new Teacher
object, how do I do it?
Something doesn't seem right about using an IoC container to achieve this, but neither does having concrete objects. Using IoC on every single object used seems excessive.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通常避免在域层中使用 IoC - 您只想尝试仅在应用程序层中访问内核(是的,您可能会经常访问内核)。
对于我的项目,我的所有业务对象通常都是 POCO,除了框架之外几乎不依赖于任何其他东西。
服务层往往有很多依赖项,但并不经常直接访问内核。
是否可以做到这一点将取决于您对 ORM 等的选择,当然还有项目的现有架构。
如果您的业务对象具有需要解决的依赖关系,那么您要么需要使用内核来解决它们,要么重构您的项目以删除依赖关系。
I generally avoid using IoC in the domain layer - you want to try and access the kernel only in the application layer (where, yes, you may access the kernel quite a lot).
For my projects, all my business objects are generally POCOs with few dependencies on anything other than framework stuff.
The service layer tends to have lots of dependencies, but doesn't access the kernel directly very often.
Whether you can do this is going to depend on your choice of ORM etc., and of course the existing architecture of the project.
If your business objects have dependencies that need to be resolved, then you are either going to need to use the kernel to resolve them, or refactor your project to remove the dependencies.
不要在 Student 和 Teacher 类 (UnitOfWork) 中具有依赖项,而是使用一个包含引用 Student 和 Teacher 类的依赖项的服务层。
这样你的实体类就可以是 POCO 的,并且可以在测试等中轻松模拟。
Instead of having dependencies in your Student and Teacher classes (UnitOfWork), have a service layer with dependencies that references the Student and Teacher classes.
This way your entity classes can be POCO's and easily mocked in tests etc.