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?
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
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With