I will implement RavenDB in the project and after a few days trying the database, I will now structure this application, but I have a question.
I write business layers for each object (almost), and I have a unique repository class that handles requests and a DocumentStore. I am confused about how I should share a DocumentStore by service level and process transactions.
I am showing an example where I am trying to save and read a document in one transaction.
Repository example:
public class RavenRepository { private static DocumentStore _store; private IDocumentSession _session; public RavenRepository(DocumentStore store) { _store = (_store==null) ? new DocumentStore() { Url = "http://wsk-gcardoso:8081" } : store; } public T SingleOrDefault<T>(Func<T, bool> predicate) where T : BaseModel { using (var session = _store.OpenSession()) { return session.Query<T>().SingleOrDefault(predicate); } } public T Add<T>(T item) where T : BaseModel { using (var session = _store.OpenSession()) { session.Advanced.AllowNonAuthoritiveInformation = this.AllowNonAuthoritiveInformation; session.Store(item); session.SaveChanges(); } return item; } public void Initialize() { _store.Initialize(); } public void Dispose() { _store.Dispose(); } }
The business layer will look like this:
public class NewsletterBusiness { private RavenRepository repository; public NewsletterBusiness(RavenRepository ravenRepository) { repository = (ravenRepository == null) ? RavenRepository(null) : ravenRepository; } public Newsletter Add(Newsletter newsletter) { Newsletter news = repository.Add(newsletter); return news; } public Newsletter GetById(long Id) { Newsletter news = repository.SingleOrDefault<Newsletter>(x => x.Id == Id); return news; } }
Now I am trying to save and read an object (newsletters) in the same transaction. From what I read, I need to set the AllowNonAuthoritativeInformation of the Store document to false in order to wait for the transaction to complete. But due to the fact that I deal with layers and repository, can I store and request db in one transaction?
To be honest, I think I got confused in OpenSession method. I think I messed up the transaction session.
For example, this code:
var repository = new RavenRepository(null); newsletterBusiness = new NewsletterBusiness(repository); repository.Initialize(); using (var tx = new TransactionScope()) { Newsletter new = newsletterBusiness.Add(new Newsletter { Title = "Created by Tests", Content = "Created By Tests" }); Newsletter objectCreated = newsletterBusiness.GetById(new.Id); repository.Dispose(); tx.Complete(); }
If I create a second business layer (for example, for images) and I set pictureBusiness.repository = repository (the same RavenRepository object set for businessLayer), will I work in the same newsletterBusiness.repository session?
picturesBusiness = new PicturesBusiness(repository); Picture pic = picturesBusiness.GetById(20);
I am very grateful for the help in this matter, Greetings from Portugal!