Skip to content

Fase I API

Johan Villegas edited this page Sep 18, 2018 · 3 revisions

Puede visualizar los commit de esta fase : Branch ApplicationLayer

4. API

El proyecto API comprende las acciones fundamentales, las cuales es exponer los EndPoint en la sección de controladores y la configuración tanto de ambiente (appsettings.json y Dockerfile), como los servicios que va a utilizar todo el ecosistema del micro-servicio (Statup.cs).

Descripcion grafica de la estructura basica de API

Descripcion de la API

Statup.cs

Es fundamental que se implemente los servicios para MediatR, DbContext y Repositorios

namespace Item.API
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Add MediatR
            var assembly = AppDomain.CurrentDomain.Load("Item.Application");
            services.AddMediatR(assembly);

            // Add DbContext using SQL Server Provider
            services.AddDbContext<ItemContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("NowDatabase")));

            // Add Repositories
            services.AddScoped<IItemRepository, ItemRepository>();

        }

    }
}

Controlador

Solo necesitamos _mediator.Send(command) para tener el enlace del command y commandHandler por medio de MediatR

namespace Item.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ItemMasterController : ControllerBase
    {
        private readonly IMediator _mediator;

        public ItemMasterController(IMediator mediator)
        {
            _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        }

        //POST: api/ItemMaster
        [HttpPost]
        public async Task<IActionResult> PostItemMaster([FromBody] CreateCommand command)
        {
            var response = await _mediator.Send(command);
            return Ok(response);
        }
    }
}