I am working on a large C# enterprise project that has significant architectural problems. One of those problems is that there are static references to a StructureMap container all over the place (static service locator). As a first step to fixing things we are passing the container into constructors and removing the static container references.
Unfortunately there are calls to the static container in entities created by Entity Framework. Pushing all those dependencies up to the clients of those entities is not feasible to do right now because of the how frequently this happens and the scope of the changes. Our goal is to remove the static container and making that many changes to do it would not be allowed by management.
I would like to inject the container into the entities when they are created by Entity Framework instead, is there a way to do this?
Thanks in advance :)
答案 0 :(得分:3)
我记得几年前我在某处读过服务可以通过构造函数注入到实体中,但我现在找不到它,所以也许我正在阅读有关IDbDependencyResolver的其他用途。
作为临时解决方案,我建议使用IHaveServiceLocator
等界面标记实体并使用ObjectMaterialized事件。
public interface IHaveServiceLocator
{
IServiceLocator ServiceLocator { get; set; }
}
然后,您创建dbContext的位置应该可以访问服务定位器,以便您可以将其设置为创建的实体。
((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (s, e) =>
{
var entity = e.Entity as IHaveServiceLocator;
if (entity != null)
{
entity.ServiceLocator = structureMapServiceLocator;
}
}