开发者

Dependency injection in domain object extension methods

开发者 https://www.devze.com 2023-02-12 02:30 出处:网络
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

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 cons开发者_开发问答tructed 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!


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消