实体框架对象实现和依赖注入 [英] Entity Framework object materialization and dependency injection

查看:118
本文介绍了实体框架对象实现和依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够通过实体框架加载和实现实体(通过查询的结果)将一些依赖项(通过使用IoC容器)注入到实体中。



可以通过挂上 ObjectMaterialized 事件,但我想知道是否有更好的方式来实现这一点,因为我使用EF 6和代码。



任何建议或想法?



谢谢



Riana

解决方案

虽然实体框架可以配置为允许将依赖关系注入实体,但我认为可以肯定的是,普遍的共识 Jimmy Bogard 的意见, Mark Seemann )根本不这样做。



对我来说要点是实体,DTO和消息之类与服务类非常不同。实体,DTO和消息是包含运行时数据的短寿命对象,而服务包含行为,通常很长寿,并且只需处理运行时数据(如实体)。



这意味着您不能将服务用于您的实体。正如马克描述的这里,不让您的实体使用服务导致贫血域模型。但是这意味着实体不应该是对象图的一部分。



相反,如果你正在练习DDD,你的实体可以简单地接受域方法的依赖您在实体上定义。这些依赖关系不能由指令处理程序提供执行用例。换句话说,依赖关系被注入到命令处理程序的构造函数中,当调用实体的domain方法时,命令处理程序将提供该方法所需的依赖关系(通常只有一个或两个)(方法注入)。 / p>

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

解决方案

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

这篇关于实体框架对象实现和依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆