Skip to content

Instantly share code, notes, and snippets.

@benfoster
Created July 20, 2012 10:54
Show Gist options
  • Save benfoster/3150146 to your computer and use it in GitHub Desktop.
Save benfoster/3150146 to your computer and use it in GitHub Desktop.
RavenDB Session Management in ASP.NET Web API with StructureMap
public class StructureMapFilterProvider : IFilterProvider
{
private readonly IContainer container;
public StructureMapFilterProvider(IContainer container)
{
this.container = container;
}
public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
{
if (configuration == null)
throw new ArgumentNullException("configuration");
if (actionDescriptor == null)
throw new ArgumentNullException("actionDescriptor");
foreach (var filter in actionDescriptor.GetFilters())
{
container.BuildUp(filter);
yield return new FilterInfo(filter, FilterScope.Action);
}
}
}
public class StructureMapConfig
{
public static void Configure()
{
ObjectFactory.Configure(cfg =>
{
cfg.For<IDocumentStore>().Singleton().Use(ConfigureDocumentStore());
cfg.For<IDocumentSession>().HttpContextScoped().Use(ctx => ctx.GetInstance<IDocumentStore>().OpenSession());
cfg.For<IFilterProvider>().Use<StructureMapFilterProvider>();
cfg.SetAllProperties(set =>
{
set.OfType<Func<IDocumentSession>>();
});
});
GlobalConfiguration.Configuration.DependencyResolver = new StructureMapResolver(ObjectFactory.Container);
}
static IDocumentStore ConfigureDocumentStore()
{
var documentStore = new DocumentStore
{
ConnectionStringName = "RavenDB"
};
documentStore.Initialize();
return documentStore;
}
}
public class RavenDbUnitOfWorkAttribute : ActionFilterAttribute
{
public Func<IDocumentSession> SessionFactory { get; set; }
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
var session = SessionFactory.Invoke();
if (session != null && actionExecutedContext.Exception == null)
{
session.SaveChanges();
}
base.OnActionExecuted(actionExecutedContext);
}
}
public class SitesController : ApiController
{
private readonly IDocumentSession session;
public SitesController(IDocumentSession session)
{
this.session = session;
}
// GET api/sites
public IEnumerable<Site> Get()
{
return session.Query<Site>().ToList();
}
// POST api/sites
[RavenDbUnitOfWork]
public HttpResponseMessage Post(Site site)
{
session.Store(site);
var response = new HttpResponseMessage(HttpStatusCode.Created);
response.Headers.Location = new Uri(Request.RequestUri, Url.Route("DefaultApi", new { controller = "site", id = site.Id }));
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment