dependancy injection

main
Peace 11 months ago
parent 486d2f7f8b
commit 5371eeab56
  1. 9
      AspNetCoreApi/Controllers/ProductController.cs
  2. 4
      AspNetCoreApi/Program.cs
  3. 20
      AspNetCoreApi/Services/ProductService.cs
  4. 3
      README.md

@ -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<ProductController> _logger;
private readonly AppDbContext _dbContext;
private readonly ProductService _service;
public ProductController(ILogger<ProductController> logger, AppDbContext dbContext)
public ProductController(ILogger<ProductController> logger, ProductService service)
{
_logger = logger;
_dbContext = dbContext;
_service = service;
}
[HttpGet(Name = "GetProduct")]
public IEnumerable<Product> Get()
{
return _dbContext.Products.ToList();
return _service.GetProducts();
}
}
}

@ -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<ProductService>();
// Add services to the container.
builder.Services.AddControllers();

@ -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<Product> GetProducts()
{
return _context.Products.ToList();
}
}
}

@ -7,4 +7,5 @@
- Middleware
- Routing
- EntityFramework
- Controller
- Controller
- Dependancy Injection
Loading…
Cancel
Save