Skip to content

Parte 13

WILSON DE OLIVEIRA JUNIOR edited this page Mar 9, 2020 · 3 revisions

[Voltar]

Padrão "UnitOfWork"

  1. Crie uma nova classe dentro do projeto Taste.Domain na pasta Interfaces chamada IUnitOfWork.cs.
  2. O código dessa classe deve ser o seguinte:
using System;
using System.Threading.Tasks;

namespace Taste.Domain.Interfaces
{
    public interface IUnitOfWork : IDisposable
    {
        ICategoryRepository Category { get; }
        Task Save();
    }
}
  1. Agora, dentro do projeto Taste.DataAccess dentro da pasta Repository crie a classe UnitOfWork.cs.
  2. Abaixo, o código da classe UnitOfWork.cs:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Taste.Domain.Interfaces;

namespace Taste.DataAccess.Repository
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly ApplicationDbContext context;

        public UnitOfWork(ApplicationDbContext _context)
        {
            context = _context;
            Category = new CategoryRepository(context);
        }

        public ICategoryRepository Category { get; private set; }

        public async Task Save()
        {
            await context.SaveChangesAsync();
        }

        public void Dispose()
        {
            context.Dispose();
        }
    }
}
  1. Altere a classe Startup.cs do projeto Taste.Web acrescentando as seguintes referências:
using Taste.Domain.Interfaces;
using Taste.DataAccess.Repository;
  1. Então altere a área ConfigureServices para que fique da seguinte forma:
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddScoped<IUnitOfWork, UnitOfWork>();

    services.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0);
    services.AddControllersWithViews().AddRazorRuntimeCompilation();
}

[Voltar]

Clone this wiki locally