I have a service class UserService that gets an instance of IDocumentStore injected using AutoFac. This is working fine but now I’m looking at code like this:
public void Create(User user)
{
using (var session = Store.OpenSession())
{
session.Store(user);
session.SaveChanges();
}
}
Every action that writes to the db uses this same structure:
using (var session = Store.OpenSession())
{
dosomething...
session.SaveChanges();
}
What is the best way to eliminate this repetitive code?
The easiest way is implementing
OnActionExecutingandOnActionExecutedon a base controller and use it.let’s imagine you create your
RavenControllerlike this:then all you need to do in your own controllers is inherit from
RavenControllerlike this:Interesting enough, I have found a blog post showing exactly this technique …
it does explain way more that what I did. I hope it helps you better