And*_*ewP 2 c# linq entity-framework dependency-injection simple-injector
有没有办法将依赖项注入从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))
Run Code Online (Sandbox Code Playgroud)
Linq/Entity Framework中是否有任何钩子允许我将对象(通过DI)传递给创建的模型?
@Oryol是正确的,施工期间,喷射应用程序组件到域对象是一个坏主意,就像它是周围的其他方式。
一种解决方案是使用方法注入而不是构造函数注入。这意味着每个域方法都将其所需的服务定义为方法参数。例如:
public bool CanLegallyVote(ISomeService service) { ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
805 次 |
| 最近记录: |