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 :)
I remember I read somewhere few years ago that services can be injected into entities through constructor, but I couldn't find it now, so maybe I was reading about IDbDependencyResolver which serves another purpose.
As a temporary solution I would suggest to mark entities with interface like IHaveServiceLocator
and use ObjectMaterialized event.
public interface IHaveServiceLocator
{
IServiceLocator ServiceLocator { get; set; }
}
And then the place where you create dbContext should have access to service locator so you can set it to entities created.
((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (s, e) =>
{
var entity = e.Entity as IHaveServiceLocator;
if (entity != null)
{
entity.ServiceLocator = structureMapServiceLocator;
}
}