Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register multiple EF contexts into a DI container

I'm starting to develop an application using Domain Driven Design concepts and applying n-layer patterns for the architecture. My problem is related to this question: because I need to create one or more database contexts.

Instead of to instantiate my contexts using the new keyword, I'm using Ninject to create a D.I. container and resolve all dependencies automatically, but here starts the confusion!

This is basically what I have here:

public interface IDataContext : IDisposable 
{ 
}

public abstract class DataContext : DbContext, IDataContext 
{
}

public class ContextA : DataContext
{
}

public class ContextB : DataContext
{
}

The first question is how to register the contexts, when they are implementing the same interface?

And the second question is how should to call the repositories, e.g.:

public class MyClass(IUserRepository userRepository, IBankRepository bankRepository)
{
  // IUserRepository is inside ContextA
  // IBankRepository is inside ContextB
}

In the sample code above, I'd like to use the same UnitOfWork. Is that possible?

like image 604
Marco Antonio Avatar asked Apr 06 '26 13:04

Marco Antonio


1 Answers

If you have users in ContextA and banks in ContextB you should reflect it in your interfaces so the repository is constructed with the context containing the expected entities :

public interface IDataContext : IDisposable 
{ 
}

public interface IContextA : IDataContext
{
   public DbSet<User> Users { get; set; } 
}

public interface IContextB : IDataContext
{
   public DbSet<Bank> Banks { get; set; } 
}

public abstract class DataContext : DbContext, IDataContext 
{
}

public class ContextA : DataContext, IContextA
{
}

public class ContextB : DataContext, IContextB
{
}
like image 132
Guillaume Avatar answered Apr 09 '26 02:04

Guillaume



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!