eestein
eestein

Reputation: 5114

How to retrieve context from instantiated POCO class?

I am using Code-First along with Entity Framework 5 and the Repository Pattern.

I need to get the context from inside some extension methods to access other entities that are not accessible through properties.

Example:

public static class MyClassExtensions
{
    public static void DoSomething(this MyClass mClass)
    {
        // This is what I want to do
        // GetContextSomeWay() is what I need
        // GetRepository is method from my context
        mClass.GetContextSomeWay().GetRepository<SomeRepository>().Where(...);
    }
}

public class MyService
{
    public void DoSomethingOnService(int id)
    {
        MyContext ctx = new MyContext();
        MyClass cl = ctx.GetRepository<MyClass>().Single(c => c.Id == id);
        cl.DoSomething();
    }
}

I thought about two solutions.

  1. Pass the context as a parameter to the extension method
  2. Set the context to each entity using the ObjectMaterialized event

Even though the first approach would work without much hassle, I can't stop thinking that this is not a good practice.

With the second, besides the work of adding a new property to each one of my classes, I was wondering if that could become a performance issue. Is this an overconcern, or is this valid?

Are there any other solutions to this problem?

Upvotes: 0

Views: 125

Answers (1)

Mare Infinitus
Mare Infinitus

Reputation: 8172

Adding Unity and placing your repository there can be a solution. You just have a container where the things live that you need, at best at the composition root.

You can access those via the Unity container then.

Here is a very good tutorial which shows the techniques needed: Jason Dollinger on MVVM. It is mainly about MVVM, but shows the usage of unity, too.

The sourcecode is available here: MVVM Demo client source code

Here is more information on those:

Unity

Composition Root

Upvotes: 1

Related Questions