Add dependency Injection

This commit is contained in:
2023-10-16 22:02:02 +02:00
parent 3e3ef39b80
commit 707bfae2e3
4 changed files with 33 additions and 6 deletions

View File

@@ -8,11 +8,11 @@ namespace GerbilManager.Controllers
[Route("gerbils")] [Route("gerbils")]
public class GerbilsController : ControllerBase public class GerbilsController : ControllerBase
{ {
private readonly InMemGerbilRepository repository; private readonly IGerbilRepository repository;
public GerbilsController() public GerbilsController(IGerbilRepository repo)
{ {
repository = new InMemGerbilRepository(); this.repository = repo;
} }
//GET /gerbils //GET /gerbils
@@ -22,5 +22,18 @@ namespace GerbilManager.Controllers
var items = repository.GetGerbils(); var items = repository.GetGerbils();
return items; return items;
} }
//GET /gerbils
[HttpGet("{id}")]
public ActionResult<Gerbil> GetGerbil(Guid id)
{
var item = repository.GetGerbil(id);
if(item is null)
{
return NotFound();
}
return item;
}
} }
} }

View File

@@ -1,3 +1,5 @@
using GerbilManager.Repositories;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add services to the container. // Add services to the container.
@@ -7,6 +9,8 @@ builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<IGerbilRepository, InMemGerbilRepository>();
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.

View File

@@ -0,0 +1,11 @@
using GerbilManager.Models;
namespace GerbilManager.Repositories
{
public interface IGerbilRepository
{
IEnumerable<Gerbil> GetGerbils();
Gerbil GetGerbil(Guid id);
}
}

View File

@@ -2,8 +2,7 @@ using GerbilManager.Models;
namespace GerbilManager.Repositories namespace GerbilManager.Repositories
{ {
public class InMemGerbilRepository : IGerbilRepository
public class InMemGerbilRepository
{ {
private readonly List<Gerbil> _gerbilList = new() private readonly List<Gerbil> _gerbilList = new()
{ {
@@ -19,5 +18,5 @@ namespace GerbilManager.Repositories
public Gerbil GetGerbil(Guid id) => _gerbilList.SingleOrDefault(x => x.Id == id); public Gerbil GetGerbil(Guid id) => _gerbilList.SingleOrDefault(x => x.Id == id);
} }
} }