user441521 user441521 - 2 months ago 14x
ASP.NET (C#) Question

ASP.NET Unity.MVC DI with EF context

I'm using Unity.MVC for DI in my ASP.NET MVC 4.6 app. I have a service interface passed into the controller and that's working great. Now I want to pass in an interface to the EF context to the service but I'm not sure how to do this. I've read EF has this IObjectContextAdapter that I could pass into my service ctor and that works, but I need to then query the actual tables on inside my service from this context but because it's an IObjectContextAdapter it doesn't know my tables. How do I do this?

public class ContactService : IContactService
//private ContactsEntities context;
private IObjectContextAdapter context;

// test ctor
public ContactService(IObjectContextAdapter ctx)
context = ctx;

// prod ctor
public ContactService()
context = new ContactsEntities();

List<Contact> GetAllContacts()
return (from c in context.ObjectContext.?? // I need to query the Contacts table that would be attached to the actual context I pass in but still keep the decoupling from using an Interface passed into the ctor



The IObjectContextAdapter is the type of ObjectContext property of DbContext.

You should subclass DbContext e.g. ContactsDatabaseContext

public class ContactsDatabaseContext : DbContext, IContactsDatabaseContext
  // ...

And then just register your ContactsDatabaseContext with your IoC container. Something like this:

container.RegisterType<IContactsDatabaseContext, ContactsDatabaseContext>();

Your ContactsDatabaseContext class and IContactsDatabaseContext interface should have properties of type DbSet<T> that refer to your tables e.g.:

IDbSet<BrandDb> Users { get; set; }


Since you are using a generated file, then do this:

public partial class ContactsDatabaseContext : IContactsDatabaseContext
  // Expose the DbSets you want to use in your services