C# : Extending Generic class - c#

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();
}
}

Related

Inferring implemented type from generic base

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.

C# OOP : Using interface with type parameters in base concrete class

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.

Interfaces and Inheritance with generics in C#

In order to use dependency injection in .NET Core, we've built a bunch of repository interfaces for our controllers to use for database interactions.
We have a EntityBase class that has some methods in it, and our generic repository interface uses that base class like: IRepository<T> where T : EntityBase.
I want to add a more specific TaggedEntityBase class that extends EntityBase to represent the fact that we have some Entities which we want to filter by tags. I want TaggedEntityBase to have an abstract property which I can use in my controller so that I can abstract out and reuse the filtering method.
So what I want is something like this, but I think I want ITaggedRepository to also inherit from IRepository so that a class implementing ITaggedRepository is guaranteed to have a ListAll method and a ListWithTags method:
public class EntityBase { }
public abstract class TaggedEntityBase : EntityBase
{
public string TagIDs { get; }
}
public interface IRepository<T> where T : EntityBase
{
IEnumerable<T> ListAll();
}
public interface ITaggedRepository<T> where T : TaggedEntityBase
{
IEnumerable<T> ListWithTags(System.Linq.Expressions.Expression<Func<T, bool>> predicate);
}
I'm fairly certain that I've just thoroughly confused myself by pursuing this line of thinking, but I'm not sure how to do what I really want here. I know I need to keep things abstract for dependency injection, but I feel like I'm butting up on the edge of what's possible with interfaces.
Is there a better line of thinking that will get me where I'm trying to go?
You can go ahead and inherit from IRepository<T>:
public interface ITaggedRepository<T> : IRepository<T> where T : TaggedEntityBase
{
IEnumerable<T> ListWithTags(Expression<Func<T, bool>> predicate);
}
At some point you may into trouble if your TaggedEntity is not really an abstraction. Say you have NamedEntities also and some are Tagged.
Now you have a INamedRepository, ITaggedRepository and a INamedTaggedRepository (you'll run into similar issues on your base entity).
You could do a more trait like thing like:
public class EntityBase {}
public interface ITagged
{
string TagIDs { get; }
}
public interface INamed
{
string Name { get; }
}
public class Book : EntityBase, ITagged, INamed
{
public string TagIDs { get; set; }
public string Name { get; }
}
public interface IRepository<T> where T : EntityBase
{
IEnumerable<T> ListAll();
}
public interface IQueryTags<T> where T : ITagged
{
IEnumerable<T> ListWithTags(Expression<Func<T, bool>> predicate);
}
public interface IQueryByName<T> where T : INamed
{
T GetByName(string name);
}
public interface IBookRepository : IRepository<Book>, IQueryTags<Book>, IQueryByName<Book>
{
}
public class ConcreteBookRepository: IBookRepository
{
public IEnumerable<Book> ListAll()
{
throw new NotImplementedException();
}
public IEnumerable<Book> ListWithTags(Expression<Func<Book, bool>> predicate)
{
throw new NotImplementedException();
}
public Book GetByName(string name)
{
throw new NotImplementedException();
}
}
In the concrete implementation you could, through composition, use a ByNameQueryer, TagQueryer and some concrete Repository.
I don't really like generic repositories, so I tend to rename IRepository to IStore since it usually only contains the CRUD aspect typically.
Oh and then some entities you can't delete, some can't be updated. You will end up breaking that down to IAdd, IUpdate, IDelete etc. This is where you start to wonder if this was actually a good idea also ;-)

Connecting different implementations with StructureMap

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.

A c# Generics question involving Controllers and Repositories

I have a base repository class which contains all the common repository methods (as generic):
public abstract class BaseRepository<T, IdType> : IBaseRepository<T, IdType>
My repositories from this base e.g.:
public class UserRepository : BaseRepository<User, int>, IUserRepository
I also have a base controller class containing common actions, and inherit from this in controllers. The repository is injected into this by DI. E.g.
public class UserController : BaseController<User>
{
private readonly IUserRepository userRepository;
public UserController (IUserRepository userRepository)
{
this.userRepository= userRepository;
}
My question is this: The base controller needs to be able to access the repository methods that are defined in the base repository. However I'm passing in via DI a different repository type for each controller (even though they all inherrit from the base repository). How can the base controller somehow access the repository that is passed in (regardless of what type it is), so that it can access the common base methods?
It all your repositories will be derived from IBaseRepository<T,IdType>, then have:
interface IUserRepository : IBaseRepository<User,int> {...}
Now any reference to a IUserRepository will know about the IBaseRepository<> members, without having to mention concrete types like the UserRepository class or BaseRepository<> class.
You can hold a reference for BaseReposiroty in BaseController
public class BaseController <T, IdType>
{
...
...
protected BaseRepository<T, IdType> Reposirory
{
{ get; set; }
}
...
...
}
Here's one way to do it..
public abstract class BaseController<TEntity, TRepository, TIdType>
where TEntity : class, new()
where TRepository : IBaseRepository<TEntity, TIdType>
{
protected TRepository Repository = RepositiryFactory.GetRepository<TEntity, TRepository>();
public IList<TEntity> GetAll()
{
return Repository.GetAll().ToList();
}
public IList<TEntity> GetAll(string sortExpression)
{
return Repository.GetAll(sortExpression).ToList();
}
public int GetCount()
{
return Repository.GetAll().Count();
}
public IList<TEntity> GetAll(int startRowIndex, int maximumRows)
{
var results = Repository.GetAll().Skip(startRowIndex).Take(maximumRows);
return results.ToList();
}
public IList<TEntity> GetAll(string sortExpression, int startRowIndex, int maximumRows)
{
var results = Repository.GetAll(sortExpression).Skip(startRowIndex).Take(maximumRows);
return results.ToList();
}
}

Categories