Skip to content

Instantly share code, notes, and snippets.

@lurumad
Last active August 29, 2015 14:24
Show Gist options
  • Select an option

  • Save lurumad/4114b2fb07adeb206f41 to your computer and use it in GitHub Desktop.

Select an option

Save lurumad/4114b2fb07adeb206f41 to your computer and use it in GitHub Desktop.
WebApi Unit of Work using DelegationHandler
public class UnitOfWorkDelegatingHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
var isSafeMethod = request.Method == HttpMethod.Get || request.Method == HttpMethod.Head;
if (!response.IsSuccessStatusCode || isSafeMethod)
{
return response;
}
var dbContext = (EntitiesDbContext)request.GetDependencyScope().GetService(typeof(EntitiesDbContext));
await dbContext.SaveChangesAsync(cancellationToken);
return response;
}
}
Copy link

ghost commented Jul 2, 2015

Viéndolo con Rodrigo, se nos ocurre si se podría optimizar para no tener que llamar al SaveChangesAsync si el request es de tipo GET por ejemplo

@lurumad
Copy link
Author

lurumad commented Jul 3, 2015

Muy buena recomendación! Lo he modificado para que funcione con los verbos considerados seguros según esta página http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

Muchas gracias!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment