views:

151

answers:

3

Say I have a nice domain model, using (constructor) DI where needed. Now I want to be able to persist this model, so I start adding infrastructure(Entity Framework) to do this. What happens now is that the persistence framework should be able to initialize your types using your IoC container.

Maybe this is possible, maybe not. Anyway, what I'm wondering now is; is it usual to use DI on you POCO classes at all? And if it is, how do I make Entity Framework use my favorite IoC container(in my case NInject) to construct my classes.

+5  A: 

It is more than OK to use IoC container to construct entities fetched from the database, I do that in my project.

ORM should not dictate your design. NHibernate can play nice with IoC Container, I have no idea about EF but I suspect it does not. I'd swap EF for NHibernate, or actually anything else if I were you.

Krzysztof Koźmic
Ok fair enough. That answers one of my questions, so I will keep using DI. I appreciate your recommendation for NH, but would really like this to work with EF.
Robert Massa
Than you might want to check out EF2, it is supposedly a lot less invasive so it's more likely it lets you plug into construction pipeline to supply services from IoC Container
Krzysztof Koźmic
I'm using EF4 with the POCO Templates, but the documentation is a bit messy and spread all over the web.
Robert Massa
+2  A: 

This is one of the religious arguments in the DDD community: should I inject services into my entities? It's really a question that you'll have to answer yourself. I"m not going to tell you what I think because it's highly contextual - what I think changes depending on several factors.

I do think you need to take a few hours and really dig deep into the archives of the ddd list to establish an answer that will work for you.

Matt Hinze
Could you maybe elaborate on which factors it depends? Thanks for the link to the ddd archive, I'll dig into that!
Robert Massa
Sure.. it depends on.. everything. What's the testing story, what does injecting enable, what are your design and architectural goals, what is your architectural style, how hard is it to debug and otherwise work with..
Matt Hinze
+1  A: 

I you would like to use EF so consider EF4 where you can use POCO templates indeed. You can implement Repositories around your POCO classes and you will be able to use IoC as you use it with another ORM. Whan you have POCO it's all about application architecture layaring.

Look at this walktrough:

http://blogs.msdn.com/adonet/pages/walkthrough-poco-template-for-the-entity-framework.aspx

Thomas Jaskula
That is exactly what I'm using :-) Also using repositories, but my objects still get instantiated by the EF. And if I want to use Lazy Loading(which required proxy classes) I need to use `context.CreateObject` from EF. This method is non-virtual and I don't see any other extension point.
Robert Massa
Thomas Jaskula