有没有办法将依赖项注入(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/