域对象扩展方法中的依赖注入
我正在 asp.net mvc 中创建一个基于节点的 Web CMS 系统。
阅读了一些有关依赖注入的书籍后,我将解决方案分成多个项目并使用抽象(抽象类和接口)。
我不知道如何解决我的 Web 项目中的以下类型的代码:
myDomainObjectNode.GetChildNodes<SomeSubNodeClass>();
如果域对象具有对 INodeRepository 的引用,我可以完成此任务,但这意味着我必须在所有域对象中携带此依赖项很麻烦,尤其是在必须创建新实例时。域对象中存在依赖项(主要是存储库)是一件坏事吗?
我的另一个想法是使用扩展方法来实现这一点。但是,扩展方法在静态类上是静态的,静态类本身无法使用 IoC 进行构造。我可以使用 INodeRepository 的 Singleton 并由 IoC 设置它来解决这个问题。
这感觉不是一个优雅的解决方案......您还有其他想法或意见吗?
谢谢你!
I'm creating a node based web CMS system in asp.net mvc.
Having read some books on dependency injection I've split my solution up into multiple projects and using abstractions (abstract classes and interfaces).
I can't figure out how to solve the following type of code in my web project:
myDomainObjectNode.GetChildNodes<SomeSubNodeClass>();
I could accomplish this if the domain object had a reference to an INodeRepository but that would mean that I have to carry this dependency around in all domain objects which is a hassle, especially when having to create new instances. Is having dependencies (mainly repositories) in you domain object a bad thing?
My other idea is to achieve this using extension methods. However, extension methods are static on a static class which itself cannot be constructed using an IoC. I could solve this using a Singleton for the INodeRepository and having it set by the IoC.
This doesn't feel like an elegant solution... do you have any other ideas or input?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通常避免授予域对象对存储库的访问权限,并尽可能隐藏任何持久性问题。
当您创建 myDomainObjectNode 时,您还可以填充子节点的集合来保存具体的对象引用。这通常是建筑商或工厂关心的问题。
我可能会放弃泛型类型来过滤集合,而只使用 Linq,您的子节点集合可能会返回
IEnumerable
。当然,您可以通过各种延迟加载和缓存策略来增强它,这是典型的 ORM 可以帮助您的。
如果您确实决定使用域对象中的存储库,我倾向于通过构造函数注入它。这使得依赖关系变得明确,并且您可以将其范围外部化。
I typically avoid giving a domain object access to repositories and hide any persistence concerns as much as possible.
When you create your myDomainObjectNode you could also fill a collection of childnodes to hold concrete object references. This would typically be a concern for a builder or factory.
I'd probably drop the generic type to filter the collection and just use Linq, your childnodes collection could return a
IEnumerable<BaseNode>
.Of course you can augment it with various deferred loading and caching strategies, something a typical ORM can help you with.
If you do decide to use a repository from your domain object I would favor to inject it through the constructor. This makes the dependency explicit and you externalize it's scope.
我最终使用 MVC DependencyResolver 在 MVC Web 项目的扩展方法中获取 INodeService 来解决这个问题。工作起来就像一个魅力,我不认为我打破了任何严肃的面向对象模式。
I ended up solving this using the MVC DependencyResolver to get an INodeService inside an extension-method in the MVC web project. Works like a charm and I don't think I've broken any serious OO-patterns.