3

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

3
  • possible duplicate of Dependency injection and Entity Framework Commented Feb 26, 2015 at 18:44
  • It's not a duplicate. I'm actually talkig about an object that has been retrieved from the database (materialized by entity framework) and on which I need to systematically inject some dependencies. He is talking about creating an object then persist it in EF. Hope I am more clear .. Commented Feb 27, 2015 at 14:24
  • Ideally, I would be able to configure EF to use an IoC container every time he wants to create a new instance of an object .. Commented Feb 27, 2015 at 14:30

1 Answer 1

5

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.