Is there a way, with EF6, to inject a custom object instance creator? What I need to do is to provide instances of entities to EF before the matrialization occurs.
basically I want to be able to define my POCO entity with non parameterless constructor, so to be able to use DI aggreate, that in the end is persisted with EF.
I've that I can achive something similar using the ObjectMaterialized event:
var oc = ( this as IObjectContextAdapter ).ObjectContext;
oc.ObjectMaterialized += ( s, e ) =>
{
//resolve and inject dependencies here using e.g. public properties
};
but I'd really love to have dependencies declared on the constructor.
Any idea? Cheers, .m
Using the default ObjectContext, I don't believe this is possible having looked at the EF code. Ultimately the objects are created by ObjectContext.CreateObject
. This does one of two things: It either calls a default constructor or else, if proxy creation is enabled, it creates the relevant proxy type. The proxy types are used for enhanced change tracking and for lazy loading properties.
However, the ObjectContext.CreateObject
is virtual, so one could override it in a derived class. That derived class would be provided with a reference to the container (or lifetime scope) and then, in the overridden CreateObject
call, this would be used to resolve the entity.
The question then becomes, how does one specify a derived type as the ObjectContext
to use for a DbContext
? Well, there is a constructor that takes an instance of the ObjectContext
the DbContext
should be using.
This is where my idea starts to go a bit off the rails, as the ObjectContext
itself needs to be told about the model it is using in the connection string. I think this might mean that a code first approach would not work as the model is lazily created and thus not available prior to the DbContext
being constructed. However, for a model first approach, maybe this could work?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With