Search code examples
entity-frameworkioc-containerninjectentity-framework-ctp5

Entity Framework CTP5 and Ninject as my IOC


Is it possible in Entity Framework CTP5 to construct retrieved persisted entities via an IOC container?

I'm using Ninject and it's tied in fine with MVC, but I need to inject some services into my domain objects when they are constructed for some business rules.

I'd rather do this using constructor injection than method or property injections.


Solution

  • I'm not sure what, exactly, you're trying to accomplish here, but EF has almost no extensbility points. The best you can do is hook into the ObjectMaterialized event fired by ObjectContext. In CTP5, you need to cast your DbContext like so in the constructor for your DbContext:

    ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += 
        this.ObjectContext_OnObjectMaterialized;
    

    And then implement your function ObjectContext_OnObjectMaterialized(object sender, ObjectMaterializedEventArgs e). You will be able to access your object, which unfortunately has already been materialized. Depending on your needs, you might be able to hack in some interesting behavior here.

    BTW, this sentence makes no sense to me:

    I need to inject some repositories into my domain objects when they are constructed for some business rules.

    Doesn't this go against Persistence Ignorant Domain Objects?