I have a dilemma about organizing my projects. I'm building an application for sending newsletters. I divided it into three projects in my solution: Newsletter.UI
(WPF), Newsletter.DAL
and Newsletter.Services
. In Newsletter.DAL
there are classes representing entities generating by EF enhanced in additional files (they are partial classes) - overriden ToString()
. In Newsletter.UI
there is of cource WPF project for presentation. The problem for me begins with Newsletter.Services
.
For now I created MailingListService.cs
:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newsletter.DAL;
namespace Newsletter.Services
{
public class MailingListService
{
private NewsletterEntities _context;
public MailingListService()
{
_context = new NewsletterEntities();
}
public List<string> GetAllMailingListsNames()
{
var query = from m in _context.MailingLists select new { m.Name };
List<string> names = new List<string>();
foreach (var m in query)
names.Add(m.Name);
return names;
}
public List<MailingList> GetAllMailingLists()
{
var query = from m in _context.MailingLists select m;
return query.ToList();
}
}
}
MessageService.cs
:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newsletter.DAL;
using System.Data.Entity;
namespace Newsletter.Services
{
public class MessageService
{
private NewsletterEntities _context;
public MessageService()
{
_context = new NewsletterEntities();
}
public List<Message> GetAllMessages()
{
return (from m in _context.Messages select m).ToList();
}
public static Message GetMessageByID(int id)
{
using (NewsletterEntities context = new NewsletterEntities())
{
Message message = (from m in context.Messages where m.MessageID == id select m).FirstOrDefault();
return message;
}
}
}
}
RecipientService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newsletter.DAL;
namespace Newsletter.Services
{
public class RecipientService
{
private NewsletterEntities _context;
public RecipientService()
{
_context = new NewsletterEntities();
}
public void addRecipient(Recipient newRecipient)
{
_context.Recipients.AddObject(newRecipient);
}
}
}
However, this gets problematic. When I open a window for creating a recipient, I create a MailingListService
instance to load mailing lists' names. Then when I try to create a new Recipient
, I create a RecipientService
instance and try to add a recipient. I get an error that I cannot use the context in different places.
How to solve this? Is my approach bad? What should it be (what should be in Services)? I don't want to get into such errors in future. I don't want to learn the MVVM approach now, I need to do this more or less the way I am doing it.