From 5371eeab562bda6e311e1ff67256439ef8deb0c1 Mon Sep 17 00:00:00 2001 From: Peace Date: Fri, 14 Jun 2024 13:36:32 +0900 Subject: [PATCH] dependancy injection --- .../Controllers/ProductController.cs | 9 +++++---- AspNetCoreApi/Program.cs | 4 ++++ AspNetCoreApi/Services/ProductService.cs | 20 +++++++++++++++++++ README.md | 3 ++- 4 files changed, 31 insertions(+), 5 deletions(-) create mode 100644 AspNetCoreApi/Services/ProductService.cs diff --git a/AspNetCoreApi/Controllers/ProductController.cs b/AspNetCoreApi/Controllers/ProductController.cs index 6267406..8cd63c1 100644 --- a/AspNetCoreApi/Controllers/ProductController.cs +++ b/AspNetCoreApi/Controllers/ProductController.cs @@ -1,5 +1,6 @@ using AspNetCoreApi.DbContexts; using AspNetCoreApi.Models; +using AspNetCoreApi.Services; using Microsoft.AspNetCore.Mvc; namespace AspNetCoreApi.Controllers @@ -9,18 +10,18 @@ namespace AspNetCoreApi.Controllers public class ProductController : ControllerBase { private readonly ILogger _logger; - private readonly AppDbContext _dbContext; + private readonly ProductService _service; - public ProductController(ILogger logger, AppDbContext dbContext) + public ProductController(ILogger logger, ProductService service) { _logger = logger; - _dbContext = dbContext; + _service = service; } [HttpGet(Name = "GetProduct")] public IEnumerable Get() { - return _dbContext.Products.ToList(); + return _service.GetProducts(); } } } diff --git a/AspNetCoreApi/Program.cs b/AspNetCoreApi/Program.cs index 54ecc85..3317913 100644 --- a/AspNetCoreApi/Program.cs +++ b/AspNetCoreApi/Program.cs @@ -1,6 +1,7 @@ using AspNetCoreApi.DbContexts; using AspNetCoreApi.Middlewares; +using AspNetCoreApi.Services; using Microsoft.EntityFrameworkCore; using Pomelo.EntityFrameworkCore.MySql; @@ -21,6 +22,9 @@ namespace AspNetCoreApi options => options .UseMySql(connString, dbServerVersion)); + // Dependancy injection + builder.Services.AddScoped(); + // Add services to the container. builder.Services.AddControllers(); diff --git a/AspNetCoreApi/Services/ProductService.cs b/AspNetCoreApi/Services/ProductService.cs new file mode 100644 index 0000000..eec4b8c --- /dev/null +++ b/AspNetCoreApi/Services/ProductService.cs @@ -0,0 +1,20 @@ +using AspNetCoreApi.DbContexts; +using AspNetCoreApi.Models; + +namespace AspNetCoreApi.Services +{ + public class ProductService + { + private readonly AppDbContext _context; + + public ProductService(AppDbContext context) + { + _context = context; + } + + public IEnumerable GetProducts() + { + return _context.Products.ToList(); + } + } +} diff --git a/README.md b/README.md index 5d697e3..c53bd21 100644 --- a/README.md +++ b/README.md @@ -7,4 +7,5 @@ - Middleware - Routing - EntityFramework - - Controller \ No newline at end of file + - Controller + - Dependancy Injection \ No newline at end of file