Last active
July 19, 2020 21:38
-
-
Save diegobfernandez/4435786 to your computer and use it in GitHub Desktop.
Exemplo de serviço com "repository" e "dependency injection"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Data.Entity; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using WebService.Persistencia.Exceptions; | |
namespace WebService.Persistencia { | |
// Implementação de IRepositorio utilizando a biblioteca Entity Framework | |
public abstract class EntityFrameworkRepositorio<T> : IRepositorio<T> where T : class { | |
protected DbContext db; | |
// É passado DbContext por parametro para que seja injetado por um container | |
protected EntityFrameworkRepositorio(DbContext context) { | |
db = context; | |
} | |
public T Insert(T item) { | |
return db.Set<T>().Add(item); | |
} | |
public void Update(object id, T item) { | |
var original = db.Set<T>().Find(id); | |
if (original == null) | |
throw new EntityNotFoundException(); | |
var entry = db.Entry(original); | |
entry.OriginalValues.SetValues(original); | |
entry.CurrentValues.SetValues(item); | |
} | |
public bool Delete(object id) { | |
var item = db.Set<T>().Find(id); | |
if (item == null) | |
throw new EntityNotFoundException(); | |
db.Set<T>().Remove(item); | |
return true; | |
} | |
public T Get(object key) { | |
var item = db.Set<T>().Find(key); | |
if (item == null) | |
throw new EntityNotFoundException(); | |
return db.Set<T>().Find(key); | |
} | |
public IQueryable<T> GetAll() { | |
return db.Set<T>(); | |
} | |
public IQueryable<T> GetFiltered(Expression<Func<T, bool>> filter) { | |
return db.Set<T>().Where(filter); | |
} | |
public IQueryable<T> GetIncluding(params Expression<Func<T, object>>[] includeProperties) { | |
IQueryable<T> query = db.Set<T>(); | |
foreach (var includeProperty in includeProperties) { | |
query = query.Include(includeProperty); | |
} | |
return query; | |
} | |
public void Salvar() { | |
db.SaveChanges(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Data.Entity; | |
using WebService.Dominio; | |
namespace WebService.Persistencia | |
{ | |
public class EntityFrameworkTodoRepositorio : EntityFrameworkRepositorio<Todo>, ITodoRepositorio { | |
public TodoRepositorio(DbContext context) : base(context) {} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace WebService.Persistencia.Exceptions { | |
public class EntityNotFoundException : Exception { | |
public EntityNotFoundException() : base("Nenhuma entidade encontrada") {} | |
public EntityNotFoundException(string message) : base(message) {} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Linq.Expressions; | |
namespace WebService.Persistencia { | |
// where T : class define que o tipo T não pode ser primitivo | |
public interface IRepositorio<T> where T : class { | |
T Insert(T item); | |
void Update(object id, T item); | |
bool Delete(object key); | |
T Get(object key); | |
IQueryable<T> GetAll(); | |
// Expression<Func<T, bool>> para definir que o tipo é uma closure ou lambda | |
IQueryable<T> GetFiltered(Expression<Func<T, bool>> filter); | |
// Expression<Func<T, bool>> para definir que o tipo é uma closure ou lambda | |
IQueryable<T> GetIncluding(params Expression<Func<T, object>>[] includeProperties); | |
void Salvar(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using WebService.Dominio; | |
namespace WebService.Persistencia | |
{ | |
public interface ITodoRepositorio : IRepositorio<Todo> {} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Ninject; | |
using Ninject.Syntax; | |
using System; | |
using System.Web.Http.Dependencies; | |
namespace ExImoveis.App_Start.Ninject | |
{ | |
// This class is the resolver, but it is also the global scope | |
// so we derive from NinjectScope. | |
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver | |
{ | |
IKernel kernel; | |
public NinjectDependencyResolver(IKernel kernel) | |
: base(kernel) | |
{ | |
this.kernel = kernel; | |
} | |
public IDependencyScope BeginScope() | |
{ | |
return new NinjectDependencyScope(kernel.BeginBlock()); | |
} | |
} | |
// Provides a Ninject implementation of IDependencyScope | |
// which resolves services using the Ninject container. | |
public class NinjectDependencyScope : IDependencyScope | |
{ | |
IResolutionRoot resolver; | |
public NinjectDependencyScope(IResolutionRoot resolver) | |
{ | |
this.resolver = resolver; | |
} | |
public object GetService(Type serviceType) | |
{ | |
if (resolver == null) | |
throw new ObjectDisposedException("this", "This scope has been disposed"); | |
return resolver.TryGet(serviceType); | |
} | |
public System.Collections.Generic.IEnumerable<object> GetServices(Type serviceType) | |
{ | |
if (resolver == null) | |
throw new ObjectDisposedException("this", "This scope has been disposed"); | |
return resolver.GetAll(serviceType); | |
} | |
public void Dispose() | |
{ | |
IDisposable disposable = resolver as IDisposable; | |
if (disposable != null) | |
disposable.Dispose(); | |
resolver = null; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace WebService.Dominio | |
{ | |
// POCO | |
public class Todo | |
{ | |
public int Id { get; set; } | |
public string Descricao { get; set; } | |
public bool Concluida { get; set; } | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using System.Net; | |
using System.Net.Http; | |
using System.Web.Http; | |
using WebService.Dominio; | |
using WebService.Persistencia; | |
namespace WebService.Controllers | |
{ | |
public class TodoController : ApiController { | |
private readonly ITodoRepositorio _repositorio; | |
// Instancia de ITodoRepositorio vai ser injetada pelo container | |
public TodoController(ITodoRepositorio repositorio) { | |
_repositorio = repositorio; | |
} | |
public IQueryable<Todo> Get() { | |
return _repositorio.GetAll(); | |
} | |
public Todo Get(int id) { | |
VerificarParametrosNulos(id); | |
return _repositorio.Get(id); | |
} | |
public HttpResponseMessage Post([FromBody] Todo todo) { | |
VerificarParametrosNulos(todo); | |
_repositorio.Insert(todo); | |
_repositorio.Salvar(); | |
var response = new HttpResponseMessage(HttpStatusCode.Created); | |
return response; | |
} | |
public void Put(int id, [FromBody] Todo todo) { | |
VerificarParametrosNulos(id, todo); | |
_repositorio.Update(id, todo); | |
_repositorio.Salvar(); | |
} | |
public void Delete(int id) { | |
VerificarParametrosNulos(id); | |
_repositorio.Delete(id); | |
_repositorio.Salvar(); | |
} | |
private static void VerificarParametrosNulos(params object[] arguments) { | |
if (arguments.Any(a => a == null)) { | |
throw new HttpResponseException(HttpStatusCode.BadRequest); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment