From 25af0ebf546bd07b9b462df2e6fcdc447fb433b2 Mon Sep 17 00:00:00 2001 From: YuukanOO Date: Fri, 4 Dec 2020 13:47:31 +0100 Subject: [PATCH] add LinkRepository backed by EF Core! --- Apps/Website/Startup.cs | 13 ++----------- Infrastructure/LinkRepository.cs | 17 +++++++++++++++++ Infrastructure/Repository.cs | 24 ++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 11 deletions(-) create mode 100644 Infrastructure/LinkRepository.cs create mode 100644 Infrastructure/Repository.cs diff --git a/Apps/Website/Startup.cs b/Apps/Website/Startup.cs index 0764120..1078bec 100644 --- a/Apps/Website/Startup.cs +++ b/Apps/Website/Startup.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using HN.Domain; using HN.Infrastructure; using MediatR; @@ -11,14 +10,6 @@ using Microsoft.Extensions.Hosting; namespace Website { - public class LinkRepository : ILinkRepository - { - public Task AddAsync(Link link) - { - throw new System.NotImplementedException("link repository not implemented yet"); - } - } - public class Startup { public Startup(IConfiguration configuration) @@ -32,9 +23,9 @@ namespace Website public void ConfigureServices(IServiceCollection services) { services.AddDbContext(options => options.UseSqlite(Configuration.GetConnectionString("Default"))); - services.AddSingleton(); - services.AddControllersWithViews(); + services.AddScoped(); services.AddMediatR(typeof(HN.Application.AddLinkCommand)); + services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/Infrastructure/LinkRepository.cs b/Infrastructure/LinkRepository.cs new file mode 100644 index 0000000..f047b11 --- /dev/null +++ b/Infrastructure/LinkRepository.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; +using HN.Domain; + +namespace HN.Infrastructure +{ + public sealed class LinkRepository : Repository, ILinkRepository + { + public LinkRepository(HNDbContext context) : base(context) + { + } + + public async Task AddAsync(Link link) + { + await base.AddAsync(link); + } + } +} \ No newline at end of file diff --git a/Infrastructure/Repository.cs b/Infrastructure/Repository.cs new file mode 100644 index 0000000..0ca047f --- /dev/null +++ b/Infrastructure/Repository.cs @@ -0,0 +1,24 @@ +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace HN.Infrastructure +{ + public abstract class Repository where TEntity : class + { + private readonly HNDbContext _context; + + protected readonly DbSet Entries; + + protected Repository(HNDbContext context) + { + _context = context; + Entries = _context.Set(); + } + + protected async Task AddAsync(params TEntity[] entities) + { + await Entries.AddRangeAsync(entities); + await _context.SaveChangesAsync(); + } + } +} \ No newline at end of file