Add dependency Injection
This commit is contained in:
@@ -8,11 +8,11 @@ namespace GerbilManager.Controllers
|
||||
[Route("gerbils")]
|
||||
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
|
||||
@@ -22,5 +22,18 @@ namespace GerbilManager.Controllers
|
||||
var items = repository.GetGerbils();
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
using GerbilManager.Repositories;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
@@ -7,6 +9,8 @@ builder.Services.AddControllers();
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
builder.Services.AddSingleton<IGerbilRepository, InMemGerbilRepository>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
|
||||
11
Repositories/IGerbilRepository.cs
Normal file
11
Repositories/IGerbilRepository.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
using GerbilManager.Models;
|
||||
|
||||
namespace GerbilManager.Repositories
|
||||
{
|
||||
public interface IGerbilRepository
|
||||
{
|
||||
IEnumerable<Gerbil> GetGerbils();
|
||||
|
||||
Gerbil GetGerbil(Guid id);
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,7 @@ using GerbilManager.Models;
|
||||
|
||||
namespace GerbilManager.Repositories
|
||||
{
|
||||
|
||||
public class InMemGerbilRepository
|
||||
public class InMemGerbilRepository : IGerbilRepository
|
||||
{
|
||||
private readonly List<Gerbil> _gerbilList = new()
|
||||
{
|
||||
@@ -19,5 +18,5 @@ namespace GerbilManager.Repositories
|
||||
|
||||
public Gerbil GetGerbil(Guid id) => _gerbilList.SingleOrDefault(x => x.Id == id);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user