views:

34

answers:

2

There are a lot of posts about how cool POCO objects are and how Entity Framework 4 supports them. I decided to try it out with domain driven development oriented architecture and finished with domain entities that has dependencies from services. So far so good. Imagine my Products are POCO objects. When i query for objects like this:

NorthwindContext db = new NorthwindContext();
var products = db.Products.ToList();

EF creates instances of products for me.

Now I want to inject dependencies in my POCO objects (products) The only way I see is make some method within NorthwindContext that makes something like pseudo-code below:

public List<Product> GetProducts(){
    var products = database.Products.ToList();
    container.BuildUp(products); //inject dependencies
    return products;
}

But what if i want to make my repository to be more flexible like this:

public ObjectSet<Product> GetProducts() { ... }

So, I really need a factory to make it more lazy and linq friendly. Please help !

+2  A: 

Are you looking for the yield keyword?

public IEnumerable<Product> GetProducts()
{
    foreach(var product in database.Products)
    {
        yield return container.BuildUp(product);
    }
}

-- 2nd Attempt:

public IEnumerable<Product> BuildUp(this IEnumerable<Product> source)
{
    foreach(var product in source)
    {
        yield return container.BuildUp(product);
    }
}

Usage:

database.Products.Where(p => blah).BuildUp();
vanja.
Thanks for your variant ! well, imagine i have 1000 products and at least half of them will load into memory on simple query database.Products.Where(x => x.Id == 50);And I should say goodbye to .Include(...) query syntax
ILICH
I have updated the answer, this should reduce unnecessary loads
vanja.
:) ok, it works for me. So, if such factory does not exist in this version of EF - i'll consider this answer as accepted. Thanks vanja !
ILICH
A: 

The answer is you shouldn't inject services into your entities. The reasoning behind this answer can be find on Jimmy Bogard's blog, as well as on my own one.

There are many problems, including:

  • confusion about what methods use the injected dependency
  • different lifecycles of entities and services
  • difficulties in testing
Szymon Pobiega
Thanks Szymon for looking at my post ! I only starting to create architecture in a domain-design way, before that i used my intention preferably. Now I have a chance to introduce kind of conceptuality in my creations, to name and organize things right and so on. The problems with dependencies are mostly lies imo in design that makes entity to be responsible for conceptually different things. We all removing persistence logic from entities because it's not the purpose of the entity itself, right ? So, why not to leave only homogeneous logic inside ?
ILICH