Reputation: 1722
Building a app with EF 6 and Ninject 3.2.2 I'm having some trouble wrapping my head around how to access the DbContext in a intelligent way.
As I understand in the newer versions of Ninject only constructor injection is encouraged. As EF 6, itself is repo and unit of work I'm not doing any abstractions on top of EF. If would like to be able to use multiple small units of works so injecting the DbContext (uow) into every class that needs it is not going to work. In a non IoC way I would do like this:
Using(var db = new DbContext){}
How do achieve this using Ninject as I no longer can do kernel.get in my using block...
Upvotes: 0
Views: 900
Reputation:
I'm not sure what you mean by "multiple small unit of works", but just for exposure, this is what I've done in a recent application:
This is an example of a repository factory
public class CartRepositoryFactory : IRepositoryFactory { public IRepository Generate(CartContext ctx) { return new CartRepository(ctx); } }
At the application service layer, I inject a UoW and the repository factory that I need
You might be asking, but why?!? This is madness!!
Well, because if the Repository manages the DbContext, then I can only do one operation per class instantiation. This allows me to open a DbContext and make several calls to the Repository. Of course now you have the same problem at application service level, you can only call one method per instantiation, but it's far easier to manage.
Ultimately it all comes down to your taste: would you rather have a thin service or a thin repository?
Upvotes: 1
Reputation: 4998
I'd consider two approaches:
Create general DbContext, which can be hidden behind an interface:
public interface IPortalContext : IDisposable
{
DbSet<User> Users { get; }
DbContext Context { get; }
}
public class PortalContext : DbContext, IPortalContext
{
public PortalContext()
: base("PortalConnectionString")
{
}
public virtual DbSet<User> Users { get; set; }
}
then you can inject your context to the constructor without problem.
Create many small contexts which can be used in different scenarios and classes.
I don't think that first approach is bad since it only encapsulates your DbSets
and DbContext
making it easier to inject and test. You don't make any unnecessary layers above EF and whole interface seems quite transparent.
Anyway this approach is better than making whole IRepository<T>
stuff to access another repository...
Upvotes: 1