将依赖项注入到Entity Framework实体和项目中 [英] Injecting dependencies into Entity Framework entities and projects

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

问题描述

是否可以将依赖项注入EF Linq context.Entities.Select(x => new Y {...})投影返回的对象中? (我使用的是Simple Injector,但概念仍然存在)

Is there a way to inject dependencies into objects returned from an EF Linq context.Entities.Select(x => new Y {...}) projection? (I am using Simple Injector, but concept remains)

我要实现的事情排序:(这只是输入,未经编译,对于任何语法错误/不完整表示抱歉)

Sort of thing I am trying to achieve: (this is just typed in, not compiled, sorry for any syntax errors/incompleteness)

// 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中是否有任何挂钩可以让我(通过DI)将对象传递给创建的模型?

Are there any hooks in Linq / Entity Framework that would allow me to pass an object (via DI) to models created?

推荐答案

ObjectContext.ObjectMaterialized事件.你可以钩上它.但是总的来说,将域服务注入域实体不是一个好主意.您可以找到许多与此主题相关的文章.

There is ObjectContext.ObjectMaterialized event. You can hook it. But in general injecting domain services into domain entities isn't good idea. You can find many articles on this subject.

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

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