c# - 将依赖项注入(inject) Entity Framework 实体和项目

标签 c# entity-framework linq dependency-injection simple-injector

有没有办法将依赖项注入(inject)从 EF Linq context.Entities.Select(x => new Y {...}) 投影返回的对象中? (我正在使用 Simple Injector,但概念仍然存在)

我正在努力实现的事情:(这只是输入,没有编译,对于任何语法错误/不完整,我们深表歉意)

// person MAY be an entity, but probably more likely a class to serve a purpose
public class Person {
  public string Name
  public DateTime DOB {get;set; }

  // what I want to achieve: note, I don't want to have complex logic in my model, I want to pass this out to a Service to determine.. obviously this example is over simplified...
  // this could be a method or a property with a get accessor
  public bool CanLegallyVote()  
  {
    return _someServiceThatWasInjected.IsVotingAge(this.DOB);
  }

  private readonly ISomeService _someServiceThatWasInjected;
  public Person (ISomeService service)
  {
    _someServiceThatWasInjected = service;
  }
}

// then calling code... I can't pass ISomeService into the "new Person", as "Additional information: Only parameterless constructors and initializers are supported in LINQ to Entities."

// If the above model represents a non-entity...
var person = context.People.Select(person => new Person {Name = x.Name, DOB = x.DateOfBirth}).First;
// OR, if the above model represents an EF entity...
var person = context.People.First();

if (person.CanLegallyVote()) {...}

// I don't want to invoke the service from the calling code, because some of these properties might chain together inside the model, I.e. I do not want to do the following:
if (_service.CanLegallyVote(person.DOB))

Linq/Entity Framework 中是否有任何钩子(Hook)允许我将对象(通过 DI)传递给创建的模型?

最佳答案

ObjectContext.ObjectMaterialized 事件。你可以钩住它。但总的来说,将领域服务注入(inject)领域实体并不是一个好主意。您可以找到很多关于这个主题的文章。

关于c# - 将依赖项注入(inject) Entity Framework 实体和项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38407102/

相关文章:

c# - 为什么我在这里得到 'Invalid attempt to read when no data is present' ?

C# 4.0 中的 C# LINQ/对象初始值设定项示例简而言之

c# - Entity Framework 5 代码优先多对多表重命名继承类 (TPC)

c# - EF Code first CTP 5 中 MapHierarchy() 的替代方案

c# - LINQ to XML 设置值,如果它不为空,否则使用构造函数的默认值

c# - LINQ to SQL where 子句验证字符串包含列表元素

c# - 如何在我的 ASP.NET ListView 中创建 If 子句?

c# - Lotus Notes 和 c# SSO

c# - 唯一列,检查现有记录,最佳方法

c# - 带有 Lambda 表达式的 LINQ - 连接、分组依据、求和和计数