I have read many questions related to this and perhaps this is a duplicate but I still can't understand this concept. From what I read this is related to covariance and contravariance.
I have these interfaces and classes:
public interface IBaseEntity
public interface IRepository<T> where T : IBaseEntity
public interface ITravelRequest : IBaseEntity
public interface IUser : IBaseEntity
public class TravelRequest : ITravelRequest
public class User: IUser
I have this controller:
public TravelRequestsController(IRepository<ITravelRequest> repository, IRepository<IUser> userRepositor)
I am trying to inject the repositories by creating them like this:
var travelRequestRepository = new Repository<TravelRequest>(context);
var userRepository = new Repository<User>(context);
var controller = new TravelRequestsController(travelRequestRepository, userRepository);
but I get this error:
Error 4 Argument 1: cannot convert from
DAL.Repository<Elite.Models.TravelRequest.TravelRequest>' to
DAL.IRepository<Elite.Models.TravelRequest.ITravelRequest>'
how can I make this work?
UPDATE - Full body of IRepository
public interface IRepository<T> where T : IBaseEntity
{
IEnumerable<T> AsQueryable();
IList<T> GetAll();
IList<T> Find(Expression<Func<T, bool>> predicate);
T Single(Expression<Func<T, bool>> predicate);
T SingleOrDefault(Expression<Func<T,bool>> predicate);
T First(Expression<Func<T, bool>> predicate);
T GetById(int id);
T Create();
void Add(T entity);
void Delete(T entity);
void Update(T entity);
void Save();
}
I could change the controllers signature but my ultimate goal is to test it with something like Moq.
Let's say IRepository<T> has an Insert(T request) method. Repository<T> implements this method as Insert(T request), meaning that Repository<TravelRequest> has an Insert(TravelRequest request) method signature, but it does not have an Insert(ITravelRequest request) signature.
To get rid of error, declare interface with out keyword.
public interface IRepository<out T> where T : IBaseEntity
{}
I was able to compile the following code successfully.
static void Main(string[] args)
{
var travelRequestRepository = new Repository<TravelRequest>();
var userRepository = new Repository<User>();
test(travelRequestRepository,userRepository);
Console.ReadLine();
}
static void test(IRepository<ITravelRequest> repository, IRepository<IUser> userRepositor)
{
}
public interface IBaseEntity{}
public interface IRepository<out T> where T : IBaseEntity
{}
public class Repository<T>:IRepository<T> where T:IBaseEntity
{
}
public interface ITravelRequest : IBaseEntity
{}
public interface IUser : IBaseEntity
{}
public class TravelRequest : ITravelRequest
{}
public class User : IUser
{ }
Related
Disclaimer: I am quite unsure of the terminology surrounding generics. Perhaps this is why I am not finding a solution by searching.
Context
Using .Net's built-in DI-container, I need to extract and inject a bunch of IEntity getters from a bunch of Repository<T> where T: IEntity.
E.g. Foo: IEntity and FooRepository: RepositoryBase<Foo>.
To save some typing, I have a
public delegate Task<T> Get<T>(Guid id);
In my program.cs I have bunch of these:
services.AddScoped<Get<Foo>>(s => s.GetRequiredService<FooRepository>().Get);
This works fine, but I am trying to write this in a more concise manner.
The best I have been able to do is:
static Get<TEntity> From<TRepo, TEntity>(IServiceProvider services)
where TRepo : RepositoryBase<TEntity> where TEntity : class, IEntity
=> services.GetRequiredService<TRepo>().Get;
which I can then use like so:
services.AddScoped<Get<Foo>>(From<FooRepository, Foo>);
I am not sure this is an improvement, since I now have repeated references to Foo.
Also, Rider is telling me that indeed <Get<Foo>> is redundant and can be removed. Doing so works and gets rid of the redundant type reference, but is a big step down in readability.
I naïvely tried just removing the second type parameter, hoping that the typesystem could infer TEntity from usages of From, but this does not work ("Cannot resolve symbol TEntity") and I cannot remove it entirely, since RepositoryBase is then missing T, and without RepositoryBase, TRepo does not contain a Get:
static Get<TEntity> From<TRepo>(IServiceProvider services)
where TRepo : RepositoryBase<TEntity> where TEntity : class, IEntity
=> services.GetRequiredService<TRepo>().Get;
Question(s):
Is there a way of delaying inference of TEntity to usage, or declaring it as "the type parameter T which the non-generic TRepo uses to implement RepositoryBase<T>"?
Or more broadly, since I suspect this could be an xy-problem:
How to write From to allow a usage such as this?:
services.AddScoped<Get<Foo>>(From<FooRepository>);
You can drastically simply your implementation by using a single non-generic repository class with generic method calls (e.g. Repository.Get<MyEntity>().
See below for a working example. Note, that in the example I'm using a generic entity Id (TKey). You can remove this if your committing to a single id type (e.g. long, Guid).
// Extension method that registers the repo
public static class ServiceCollectionExtensions
{
public static void AddRepositories(this IServiceCollection services)
=> services.AddScoped<IRepository, Repository>();
}
// Example Usage in Startup.cs (or Program.cs)
public void ConfigureServices(IServiceCollection services)
=> services.AddRepositories();
//Example usage - note -now just register repo and DI will wire up ctors
var repo = services.GetRequiredService<Repository>();
var entity = repo.Get<Foo>(x => x.Id == 1234);
var entities = repo.GetAll<Foo>().Where(x => x.Prop1 > blah).ToList();
//////////////////////////MOCK IMPLEMENTATION///////////
// ENTITY
public interface IEntity<TKey>
where TKey : unmanaged
{
TKey Id { get; set; }
}
public class Foo: IEntity<int>
{
public int Id { get; set; }
}
// REPOSITORY
public interface IRepository
{
IQueryable<TEntity> GetAll<TEntity>() where TEntity : class;
IQueryable<TEntity> GetAll<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class;
TEntity Get<TEntity>(Func<TEntity, bool> predicate) where TEntity : class;
Task<TEntity> GetAsync<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class;
}
public class Repository : IRepository
{
DbContext _dbContext;
public Repository(DbContext context) => _dbContext = context;
public IQueryable<TEntity> GetAll<TEntity>() where TEntity : class
=> _dbContext.Set<TEntity>();
public IQueryable<TEntity> GetAll<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
=> _dbContext.Set<TEntity>().Where(predicate)!;
public TEntity Get<TEntity>(Func<TEntity, bool> predicate) where TEntity : class
=> _dbContext.Set<TEntity>().FirstOrDefault(predicate)!;
public Task<TEntity> GetAsync<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
=> _dbContext.Set<TEntity>().FirstOrDefaultAsync(predicate)!;
}
The usual way to use DI for generic types would be;
public interface IRepository<T>{
Task<T> Get(Guid id);
}
public class RepositoryBase<T> : IRepository<T> { ... }
public class FooRepository : RepositoryBase<Foo> { ... }
services.AddScoped<IRepository<Foo>,FooRepository>();
public class Something{
public Something(IRepository<Foo> repository){...}
}
Sure, the consumer of your service now needs the entire interface, rather than just the Get delegate. But this has much lower code complexity, and runtime overheads.
Then if you want to register separate services for different aspects of your repositories, but without the over head of allocating multiple instances;
public interface IGetRepository<T>{
Task<T> Get(Guid id);
}
public interface IPutRepository<T>{
Task Put(T);
}
public class RepositoryBase<T> : IGetRepository<T>, IPutRepository<T> { ... }
services.AddScoped<FooRepository>();
services.AddScoped<IGetRepository<Foo>>(s => s.GetRequiredService<FooRepository>());
services.AddScoped<IPutRepository<Foo>>(s => s.GetRequiredService<FooRepository>());
With a helper method to register each repository. Or by scanning the types in your assembly to auto-register all repositories.
I can answer the How to write From question.
But you have to modify other things too:
public delegate Task<T> Get<T>(Guid id);
public class Foo
{
}
public interface IRepository<T>
{
Task<T> Get(Guid id);
}
public abstract class Repository<T> : IRepository<T>
{
public abstract Task<T> Get(Guid id);
}
public class FooRepository : Repository<Foo>
{
public override async Task<Foo> Get(Guid id)
{
await Task.CompletedTask;
return new Foo();
}
}
public void RegisterServices(IServiceCollection services)
{
services.AddScoped<IRepository<Foo>, FooRepository>();
services.AddScoped<Get<Foo>>(From<Foo>);
}
public static Get<T> From<T>(IServiceProvider provider)
{
return provider.GetRequiredService<IRepository<T>>().Get;
}
But you end up with a pretty clean From.
You may have issues, if missing repositories for some T.
However, the usual way is to just inject the repository and call it directly.
I hope the title is descriptive of the problem, I had trouble phrasing the problem I am trying to solve.
I'm using .NET Core 2.1
I've recently started at a C# shop after doing Python for the last 5 years so my strongly typed oop is a bit rusty. Here is what I have and what I'm trying to do:
I a base repository interface that defines basic CRUD functionality for database entities:
public interface IRepository<TEntity, TPrimaryKey> where TEntity : class
{
TEntity FindById(TPrimaryKey id)
void Create(TEntity entity);
void Delete (TEntity entity);
}
I inherit from this interface to define the interface that my repository class implements:
interface IProductRepository : IRepository<Product, int>
{
void SomeProductRepoMethod(int someParam);
}
Then I implement all interface methods in my concrete class:
public class ProductRepository : IProductRepository
{
public Product FindById(int id)
{
// lookup
}
public void Create(Product product)
{
// save
}
public void SomeProductRepoMethod(int someParam)
{
// do product repository specific stuff
}
....
}
Now, what I want to do is fairly straightforward. I want to add a overload of Create on IRepository that takes an IEnumerable of TEntity :
public interface IRepository<TEntity, TPrimaryKey> where TEntity : class
...
void Create(IEnumerable<TEntity> entities);
...
But I'd like to define the implementation of this overload once:
So I was thinking I could make a abstract base repository class to put the above implementation. The problem I am facing is I'm not sure how or even if I could do this cleanly with the modelI have now. I tried to make a base class that implements IRepository, but that would mean
passing type params to the base class and on to the interface:
public abstract class BaseRepository<TEntity, TPrimaryKey> : IRepository<TEntity, TPrimaryKey>
{
public abstract TEntity FindById(TPrimaryKey id);
public abstract void Create(TEntity entity);
public abstract void Delete(TEntity entity);
public void Create(IEnumerable<TEntity> entities)
{
foreach(TEntity entity in entities)
{
Create(entity);
}
}
}
Then in my concrete repository:
public class ProductRepository : BaseRepository<Product, int>, IProductRepository
{
public override Product FindById(int id)
{
// lookup
}
public override void Create(Product product)
{
// save
}
public void SomeProductRepoMethod(int someParam)
{
// do product repository specific stuff
}
....
}
This doesn't feel quiet right to me since I am passing the same type params in both IProductRepository and ProductRepository. I feel like
I'm close but not there and I'm not sure what the best practice approach here would be. If anyone could suggest an approach I would really
appreciate the feedback. Apologies for the length of the post but I felt I needed to clearly describe what I was trying to do. Thanks!
Having the same type parameters in an interface and an abstract class is not that big of a deal. Using your abstract class solution is okay, unless your ProductRepository needs to inherit from some other class.
Actually, with your abstract class, your IRepository interface doesn't need to exist anymore. Just handle everything with BaseRepository!
Another solution to this problem is an extension method. In a static class, you can write this:
public static void Create<TEntity, TPrimaryKey>(this IRepository<TEntity, TPrimaryKey> repo, IEnumerable<TEntity> entities) where TEntity : class {
// do your foreach loop here
}
Now you can call this method on any IRepository instance just like this:
repository.Create(...);
Here's the way I'd do it. I'd break the inheritance between IRepository and IProductRepository:
Here are your interfaces:
public interface IRepository<TEntity, TPrimaryKey> where TEntity : class
{
TEntity FindById(TPrimaryKey id);
void Create(TEntity entity);
void Delete(TEntity entity);
void Create(IEnumerable<TEntity> entities);
}
internal interface IProductRepository
{
void SomeProductRepoMethod(int someParam);
}
Then let your base class inherit IRepository as you've done:
base class:
public abstract class BaseRepository<TEntity, TPrimaryKey> :
IRepository<TEntity, TPrimaryKey> where TEntity : class
{
public abstract TEntity FindById(TPrimaryKey id);
public abstract void Create(TEntity entity);
public abstract void Delete(TEntity entity);
public void Create(IEnumerable<TEntity> entities)
{
foreach (TEntity entity in entities)
{
Create(entity);
}
}
}
and then you derive your base class and also implement your IProductRepository:
public class ProductRepository : BaseRepository<Product, int>, IProductRepository
{
public override Product FindById(int id)
{
// find
}
public override void Create(Product product)
{
// save
}
public void SomeProductRepoMethod(int someParam)
{
// do product repository specific stuff
}
public override void Delete(Product entity)
{
// delete
}
}
I think your derived class' specificity to being a Product repository is an implementation detail on BaseRepository.
I have Interface IRepository and Class Repository with parameter constructor which Implement IRepository. Both Class and Interface are generic. I want to pass this parameter while registering. The code is as follows:
public interface IRepository<T> where T : class, new()
{
public Task<int> InsertAsync(T entity);
}
public class Repository<T> : IRepository<T> where T : class, new()
{
public MobileServiceClient MobileService { get; set; }
public Repository(MobileServiceClient mobileService)
{
MobileService = mobileService;
}
public async Task<int> InsertAsync(T entity)
{
var table = MobileService.GetSyncTable<T>();
await table.InsertAsync(entity);
return 1;
}
}
I did generic class registration like this
Container.Register(typeof(IRepository<>), typeof(Repository<>));
I am not finding way to pass parameter while registering.
partial class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
}
My generic repository implements a common set of methods for TEntity like
public TEntity Get(int id)
{
return _context.Set<TEntity>()
.Find(id);
}
public TEntity Get(Expression<Func<TEntity, bool>> predicate)
{
return _context.Set<TEntity>()
}
which I can access like
Repository<User>().Get();
Many repositories does the same set of operation, so it is beneficial but now I want to extend Repository<User> to support some additional behavior.
partial class Repository<User> : IRepository<User>
{
public user DoMagicFunction()
{
}
}
so that I can use the repository like
Repository<User>().DoMagicFunction();
how can I extend the same generic class for Some Tentity to extend new behaviour instead of modifying it.
I could have done the same like creating another UserRepository to support new feature, but the accessor would become
UserRepository.DoMagicFunction();
but I want it to be like
Repository<User>().DoMagicFunction();
You can use an extension method:
public static class ExtensionMethods {
public static User DoMagicFunction(this Repository<User> repository) {
// some magic
return null; //or another user
}
}
This will thus add the function in a syntactically nice way to Repository<User> objects.
In case you want to support it not only for Users, but for subclasses of Users as well, you can make the function generic:
public static class ExtensionMethods {
public static TEntity DoMagicFunction<TEntity>(this Repository<TEntity> repository)
where TEntity : User {
// some magic
return null; //or another TEntity
}
}
C# has a language feature called Extension Methods, you probably are using them from the .NET framework without knowing (e.g. the linq extensions methods). It's common to extend your classes or even your interfaces with extension methods without breaking the functionality of your code. Here is an example for your case.
Suppose you have a generic IRepository interface:
public interface IRepository<TEntity> where TEntity : class, IEntity
{
IQueryable<TEntity> Entities { get; }
}
This interface adheres to the SOLID principles, especially the O and I principle.
Now suppose IEntity looks like this:
public interface IEntity
{
int Id { get; }
}
Now you could perfectly imagine an often reusable extension method like this:
public static class RepositoryExtensions
{
// similar to your MagicFunction
public static TEntity GetById<TEntity>(this IRepository<TEntity> repository, int id)
where TEntity : class, IEntity
{
return repository.Entities.Single(entity => entity.Id == id);
}
}
In a similar manner you could also extend your Repository class
public static class RepositoryExtensions
{
public static TEntity GenericMagicFunction<TEntity>(this Repository<TEntity> repository)
{
//do some stuff
}
}
You can now consume that like this:
var repository = new Repository<User>();
var user = repository.GenericMagicFunction();
You could also limit your extension method:
public static class RepositoryExtensions
{
public static User DoMagicFunction(this Repository<User> repository)
{
//do some stuff
}
}
But doing this will defeat it's purpose, you could rather just implement this in the Repository<User> class.
If your system and architecture uses Dependency Injection, you're probably injecting an IRepository<User> to your consuming classes. So the first or second extension method examples I've provided would make the most sense.
If you want to extend any repository you can do it like this.
public static class RepositoryExtension
{
public static void MagicMethod<TEntity>(this IRepository<TEntity> repo) where TEntity: class
{
....
}
}
For a specific repository (eg User repository) you can use a similar process
public static class RepositoryExtension
{
public static void MagicMethod(this IRepository<User> repo)
{
....
}
}
Extension methods are not the way to go, because the code that implements the method can only access public/internal members of the class they extend and you are likely to want your repository's DataContext to be private.
In my opinion, your approach needs to be changed slightly.
What if in the future you want to add a Delete method to your generic repository, but you have some entities that should never be deleted? You'll end up with an instance of a repository for something like PurchaseOrder that you'll either have to remember to never call delete on or you will have to create a descendant of Repository<T> that throws an InvalidOperationException if called. Both of which are poor implementations.
Instead, you should delete your IRepository<T> interface completely. Keep your Repository<T> class, but explicitly define a repository interface for every entity that only has the methods you require.
public class Repository<TKey, TEntity>......
{
public TEntity Get<TEntity>(TKey key)....
public void Delete(TEntity instance)....
...etc...
}
public interface IPurchaseOrderRepository {
PurchaseOrder Get(int orderNumber);
// Note: No delete is exposed
}
MyDependencyInjection.Register<IPurchaseOrderRepository, Repository<PurchaseOrder, int>>();
When you need additional methods on your repository you add them to your IPurchaseOrderRepository and create a descendant of Repository<T>
public interface IPurchaseOrderRepository {
PurchaseOrder Get(int orderNumber);
void DoSomethingElse(int orderNumber);
}
public class PurchaseOrderRepository: Repository<PurchaseOrder, int> {
public void DoSomethingElse(int orderNumber) {.......}
}
MyDependencyInjection.Register<IPurchaseOrderRepository, PurchaseOrderRepository>();
Extension method is a best choice for this case.
Note: I have not checked but you should check Dependency Injection still works well as normal.
You can use below code for testing:
public class Employee
{
}
public class User
{
}
public interface IRepo<TEntity> where TEntity : class
{
TEntity Get(int id);
DbSet<TEntity> Get(Expression<Func<TEntity, bool>> predicate);
DbContext GetContext();
}
public class Repo<TEntity> : IRepo<TEntity> where TEntity : class
{
DbContext _context;
public TEntity Get(int id)
{
return _context.Set<TEntity>()
.Find(id);
}
public DbSet<TEntity> Get(Expression<Func<TEntity, bool>> predicate)
{
return _context.Set<TEntity>();
}
public DbContext GetContext()
{
return _context;
}
}
public static class RepoExtensions
{
public static ChangeTracker DoMagic(this Repo<User> userRepo)
{
return userRepo.GetContext().ChangeTracker;
}
}
public static class Test
{
public static void DoTest()
{
Repo<User> repoUser = new Repo<User>();
repoUser.DoMagic();
Repo<Employee> repoEmployee = new Repo<Employee>();
//repoEmployee.DoMagic();
}
}
I have a pretty straightforward generic repository:
public interface IRepository<TEntity, TNotFound>
where TEntity : EntityObject
where TNotFound : TEntity, new()
{
IList<TEntity> GetAll();
TEntity With(int id);
TEntity Persist(TEntity itemToPersist);
void Delete(TEntity itemToDelete);
}
I want to define a contract for a repository for the type Term without any special behaviour. So it looks like this:
public class TermNotFound : Term
{ public TermNotFound() : base(String.Empty, String.Empty) { } }
public interface ITermRepository : IRepository<Term, TermNotFound> { }
Now for testing, I want to create an in-memory implementation of the generic repo, so I have this (not finished for brevity):
public class InMemoryRepository<TEntity, TNotFound> : IRepository<TEntity, TNotFound>
where TEntity : EntityObject
where TNotFound : TEntity, new()
{
private IList<TEntity> _repo = new List<TEntity>();
public IList<TEntity> GetAll()
{
return this._repo;
}
public TEntity With(int id)
{
return this._repo.SingleOrDefault(i => i.Id == id) ?? new TNotFound();
}
public TEntity Persist(TEntity itemToPersist)
{
throw new NotImplementedException();
}
public void Delete(TEntity itemToDelete)
{
throw new NotImplementedException();
}
}
It's not hard to see how I want it to work. For my tests, I want the generic InMemoryRepository implementation to be injected to create my ITermRepository. How hard is that right?
Well, I can't get StructureMap to do it. I have tried using WithDefaultConventions and ConnectImplementationsToTypesClosing(typeof(IRepository<,>)) in the scanner without success.
Can someone please help me out?
Your InMemoryRepository doesn't implement ITermRepository interface. That's why you can't connect them.
The best thing you could do with what you have is injecting InMemoryRepository<Term, TermNotFound> for IRepository<Term, TermNotFound>.
If you really need to inject ITermRepository, then you'll need to have another repository class inheriting from InMemoryRepository and implementing ITermRepository:
public class InMemoryTermRepository
: InMemoryRepository<Term, TermNotFound>, ITermRepository
{
}
Now you can connect ITermRepository to InMemoryTermRepository using:
.For<ITermRepository>().Use<InMemoryTermRepository>()
If you have many interfaces like ITermRepository, you could create a StructureMap convention, to connect I...Repository to InMemory...Repository. The default convention is to connect IClass to Class.