Generic Repository Pattern for ASP.NET Core

Part 2: Separate database concern & avoid repetitive code

Why Repository Pattern?

public Author getAuthorById(String authorId)
public List<Author> getAuthor()
public Author createAuthor(Author author)
public Author editAuthor(Author author)
public void DeleteAuthor(String authorId)

Why Generalize Repository Pattern?

Generic Repository Pattern

Add Base Model

Models/

Add Domain Models

Models/

Add Generic Repository

Repositories/

Configure Database Context

Repositories/

Configure Repository for Dependency Injection

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DatabaseContext>(opts =>
opts.UseInMemoryDatabase("database"));
services.AddScoped<DatabaseContext>();
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
services.AddControllers();
}

Use Generic Repository in Application

Controllers/
Create Book
curl -k --request POST https://localhost:5001/book \
--header "Content-Type: application/json" \
--data '{ "Title":"BookTitle" }'
Get Books
curl -k https://localhost:5001/book
Get Book By Id
curl -k https://localhost:5001/book/c43193d6-33c9-4e0b-acb7-ee7fa560

Making Generic Repository Approach more flexible

Repositories/
ConfigureService →
services.AddScoped<IAuthorRepository, AuthorRepository>();
Controllers/
Repository.cs
public Task<T> FindByCondition(Expression<Func<T, bool>> predicate)
=> context.Set<T>().FirstOrDefaultAsync(predicate);
AuthorRepository.cs
public Task<Author> GetByName(string name) {
return FindByCondition(author => author.Name == name);
}
Create Author
curl -k --request POST https://localhost:5001/author \
--header "Content-Type: application/json" \
--data '{ "Name":"AuthorName" }'
Get Author By Name
curl -k https://localhost:5001/author/AuthorName

Repository Approach Visualized

git clone https://github.com/udarabibile/aspnetcore-webapi.git
cd aspnetcore-webapi
git checkout generic-repository
dotnet restore
dotnet run (or dotnet watch run)

Full Stack Developer | BiBi

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store