Reputation: 1236
I have been trying to implement a generic repository in MVC with Unit of Work and Dependency Injection with Ninject.
The post I have been following is this one http://codefizzle.wordpress.com/author/darkey69/
I am not getting anything returned when I try to use the repository in my controllers. I suspect it is because there is nothing that specifically links or injects the EFDbContext and cannot seem to work out how to do this.
If anyone has implemented this and can assist that would be greatly appreciated. I won't re-post my code just yet as it is all contained and explained in the post above.
Upvotes: 0
Views: 1299
Reputation: 239200
While, ultimately, I would discourage you from using the UoW/Repository patterns with an ORM like Entity Framework, I can still give you an approach I've toyed with, which may be helpful even in something more appropriate to abstracting your context, like a service.
All the link you posted is doing is using generics so you don't have to actually define separate implementations of IRepository
for each particular entity type. However, you still must manually new up an instance of the generic repository for each entity type in your IUnitOfWork
implementation and alter the interface itself to include each entity's repository instance if you want to actually be able to work with the interface instead of the actual generic instance. Not only is that cumbersome, but it also violates open-closed on both UnitOfWork<T>
and IUnitOfWork
, and keeping them in sync with changes is going to be loads of fun, as well (read: sarcasm).
An alternative I've toyed with, though I won't go so far as to recommend it, is to use generic methods instead of generic classes. For example, instead of something like:
public class Repository<T> : IRepository<T>
where T : class
{
...
public IEnumerable<T> GetAll()
{
return _dbSet;
}
}
You might do:
public class Repository : IRepository
{
...
public IEnumerable<T> GetAll<T>()
where T : class
{
return context.Set<T>();
}
}
Which means, you only need to new up one Repository
instance, and you can then access any entity type in your context off that:
var repo = new Repository(context);
var foos = repo.GetAll<Foo>();
var bars = repo.GetAll<Bar>();
This, of course, negates the need entirely for a unit of work.
The reason I won't necessarily recommend this approach is that it hasn't been field tested. As I've said, I've toyed around with it personally a bit, and I feel comfortable with it myself. However, I'd very much be interested to hear what other developers think of this approach.
Upvotes: 1