EF, Unit of Work, and Repository

10/17/12

EF, Unit of Work, and Repository

For anyone using Entity Framework, read this post:

Tip 18 – How to decide on a lifetime for your ObjectContext

The more you use an ObjectContext, generally the bigger it gets. This is because it holds a reference to all the Entities it has ever known about, essentially whatever you have queried, added or attached.

DbContext wraps ObjectContext, so this is still relevant.

I was wondering why Microsoft didn’t implement this using weak references to avoid this issue. It finally hit me.

class Program
{
    static void Main()
    {
        var repo = new Repository();

        var entity = repo.GetEntity();

        entity.Name = "Test";

        // entity is now eligible for garbage collection
        GC.Collect();  // Never in production code!

        repo.SaveChanges();
    }
}

public class Repository
{
    private WeakReference _reference;

    public Entity GetEntity()
    {
        var result = new Entity();
        _reference = new WeakReference(result);
        return result;
    }

    public void SaveChanges()
    {
        var entity = _reference.Target as Entity;

        if (entity == null)
        {
            Console.WriteLine("Oops - nothing saved.");
        }
        else
        {
            Console.WriteLine("Entity saved OK.");
        }
    }
}

public class Entity
{
    public string Name { get; set; }
}

Here’s the really fun part - the behavior changes between Debug and Release configurations.

In other words, using weak references here is a Really Bad Idea.


Your Host: webmaster@truewill.net
Copyright © 2000-2013 by William Sorensen. All rights reserved.