Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

ioc container - Entity Framework object materialization and dependency injection

I would like to be able to inject some dependencies (by using an IoC container) into entities just after they are loaded and materialized by Entity Framework (as a result of a query for instance).

It is possible to do so by hooking on the ObjectMaterialized event but I'm wondering if there is no better manner to achieve this as I use EF 6 and code first.

Any advices or ideas ?

Thanks

Riana

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Although Entity Framework can be configured to allow dependencies to be injected into entities, I think it's safe to say that the general consensus (take a look at the opinions of Jimmy Bogard, Mark Seemann and me) is to not do this at all.

For me the main point is that classes like entities, DTOs and messages are very different from service classes. Entities, DTOs and messages are short lived objects containing runtime data, while services contain behavior, are often long lives and simply process runtime data (such as entities).

That doesn't mean that you can't use services into your entities though. As Mark describes here, not letting your entities use services lead to an Anemic Domain Model. But what this means is that entities shouldn't be part of your object graph.

Instead, if you are practicing DDD, your entities can simply accept dependencies into the domain methods that you define on the entities. Those dependencies can than be supplied by the command handlers that execute the use case. In other words, dependencies are injected into the constructor of a command handler, and when calling an entity's domain method, the command handler will supply the dependencies that this method requires (usually just one or two) to that method (method injection).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...