본문 바로가기
.NET Microservices

.NET Microservices] 3. 샘플 프로젝트 - PlatformService

by Fastlane 2023. 4. 18.
728x90
반응형

출처 : https://youtu.be/DgVjEo3OGBI

1. webapi project 생성 및, 필요한 기본 package 추가 

PS C:\Project\Microservices> dotnet --version 
6.0.202
PS C:\Project\Microservices> dotnet new webapi -n PlatformService
PS C:\Project\Microservices> code -r PlatformService
PS C:\Project\Microservices\PlatformService> dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection
PS C:\Project\Microservices\PlatformService> dotnet add package Microsoft.EntityFrameworkCore
PS C:\Project\Microservices\PlatformService> dotnet add package Microsoft.EntityFrameworkCore.Design
PS C:\Project\Microservices\PlatformService> dotnet add package Microsoft.EntityFrameworkCore.InMemory
PS C:\Project\Microservices\PlatformService> dotnet add package Microsoft.EntityFrameworkCore.SqlServer

2. Model 생성

using System.ComponentModel.DataAnnotations; //CTRL + . 

namespace PlatformService.Models
{
    public class Platform
    {
        [Key]
        [Required]
        public int Id { get; set; } //Prop + tab하면 자동으로 소스 생성
        [Required]
        public string Name { get; set; }
        [Required]
        public string Publisher { get; set; }
        [Required]
        public string Cost { get; set; }
    }
}

3. DB Context 생성

AppDbContext.cs

using Microsoft.EntityFrameworkCore;
using PlatformService.Models;

namespace PlatformService.Data
{
    public class AppDbContext : DbContext
    {
    	//CTOR + TAB 하면 자동으로 constructor 생성됨
        public AppDbContext(DbContextOptions<AppDbContext> opt) : base(opt)
        {
            
        }

        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            // in memory database used for simplicity, change to a real db for production applications
            options.UseInMemoryDatabase("InMem");
        }

        public DbSet<Platform> Platfoorms { get; set; }
    }
}

Program.cs

using PlatformService.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddDbContext<AppDbContext>();

4. Repository 설정

IPlatformRepo.cs

using PlatformService.Models;

namespace PlatformService.Data
{
    public interface IPlatformRepo
    {
        bool SaveChanges();

        IEnumerable<Platform> GetAllPlatforms();
        Platform GetPlatformById(int id);
        void CreatePlatform(Platform plat);
    }
}

PlatformRepo.cs

using PlatformService.Models;

namespace PlatformService.Data
{
    public class PlatformRepo : IPlatformRepo
    {
        private readonly AppDbContext _context;

        public PlatformRepo(AppDbContext context)
        {
            _context = context;
        }
        public void CreatePlatform(Platform plat)
        {
            if (plat == null)
            {
                throw new ArgumentNullException(nameof(plat));
            }
            
            _context.Platforms.Add(plat);
        }

        public IEnumerable<Platform> GetAllPlatforms()
        {
            return _context.Platforms.ToList();
        }

        public Platform GetPlatformById(int id)
        {
            return _context.Platforms.FirstOrDefault(p => p.Id == id);
        }

        public bool SaveChanges()
        {
            return (_context.SaveChanges() >= 0);
        }
    }
}

Program.cs

//dependency injection을 등록한다. 
builder.Services.AddScoped<IPlatformRepo, PlatformRepo>();

5. 임시 데이터 설정

PrepDb.cs

using PlatformService.Models;

namespace PlatformService.Data
{
    public static class PrepDb
    {
        public static void PrepPopulation(IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                SeedData(serviceScope.ServiceProvider.GetService<AppDbContext>());
            }


        }

        private static void SeedData(AppDbContext context)
        {
            if(!context.Platforms.Any())
            {
                Console.WriteLine("--> Seeding Data...");
                context.Platforms.AddRange(
                    new Platform() {Name="Dot Net", Publisher="Microsoft", Cost="Free"},
                    new Platform() {Name="SQL Server Express", Publisher="Microsoft", Cost="Free"},
                    new Platform() {Name="Kubernetes", Publisher="Cloud Native Computing Foundation", Cost="Free"}
                );

                context.SaveChanges();
            }
            else
            {
                Console.WriteLine("--> We already have data");
            }
        }
    }
}

Program.cs

PrepDb.PrepPopulation(app);

app.Run();

6. DTO 생성

namespace PlatformService.Dtos
{
    public class PlaformReadDto
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Publisher { get; set; }
        public string Cost { get; set; }
    }
}
using System.ComponentModel.DataAnnotations;

namespace PlatformService.Dtos
{    
    public class PlaformCreateDto
    {
        [Required]
        public string Name { get; set; }
        [Required]
        public string Publisher { get; set; }
        [Required]
        public string Cost { get; set; }

    }
}

7. AutoMapper 설정

builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
using AutoMapper;
using PlatformService.Dtos;
using PlatformService.Models;

namespace PlatformService.Profiles
{
    public class PlatformsProfile : Profile
    {
        public PlatformsProfile()
        {
            // Source -> Target
            CreateMap<Platform, PlaformReadDto>();
            CreateMap<PlaformCreateDto, Platform>();
        }
    }
}

8. Controller 생성 및 Action Method 추가 

using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using PlatformService.Data;
using PlatformService.Dtos;
using PlatformService.Models;

namespace PlatformService.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PlatformsController : ControllerBase
    {
        private readonly IPlatformRepo _repository;
        private readonly IMapper _mapper;

        public PlatformsController(IPlatformRepo repository, IMapper mapper)
        {
            _repository = repository;
            _mapper = mapper;
        }

        [HttpGet]
        public ActionResult<IEnumerable<PlatformReadDto>> GetPlatforms()
        {
            Console.WriteLine("--> Getting Platforms....");

            var platformItem = _repository.GetAllPlatforms();

            return Ok(_mapper.Map<IEnumerable<PlatformReadDto>>(platformItem));
        }

        [HttpGet("{id}", Name = "GetPlatformById")]
        public ActionResult<PlatformReadDto> GetPlatformById(int id)
        {
            var platformItem = _repository.GetPlatformById(id);

            if (platformItem != null)
            {
                return Ok(_mapper.Map<PlatformReadDto>(platformItem));
            }

            return NotFound();
        }

        [HttpPost]
        public ActionResult<PlatformReadDto> CreatePlatform(PlatformCreateDto platformCreateDto)
        {
            Console.WriteLine("--> Getting Platforms....");

            var platformModel = _mapper.Map<Platform>(platformCreateDto);

            _repository.CreatePlatform(platformModel);
            _repository.SaveChanges();

            var PlatformReadDto = _mapper.Map<PlatformReadDto>(platformModel);

            return CreatedAtRoute(nameof(GetPlatformById), new { Id = PlatformReadDto.Id }, PlatformReadDto);
        }
    }
}

Service 폴더구조

9. API TEST

728x90
반응형

댓글