I have a simply Class that is intended to be a simple POCO - it just holds data. With one exception: It contains a Collection of Notes. I want to lazy-load this collection so that I don't have to fetch the Notes on Pages that don't need them. The stub for this is this:
public class MyDTOClass
{
private ICollection<Note> _notes = null;
public ICollection<Note> Notes
{
get
{
if(_notes == null)
{
// Get an INoteRepository and initialize the collection
}
return _notes;
}
}
}
Now, I'm wondering how to proceed from here. It's an ASP.net MVC application and I use Dependency Injection to inject the IRepositories in classes that need them, for example my controllers. But as this class here is supposed to be a really simple DTO, I'm reluctant to inject an INoteRepository into it, also because the caller shouldn't worry or care about the fact that this is lazy-loaded.
So I'm thinking of having another Class in my Model that holds a INoteRepository.
public class MyDataAccessClass
{
private INoteRepository _noteRepo;
// Inject is part of Ninject and makes sure I pass the correct
// INoteRepository automatically
[Inject]
public MyDataAccessClass(INoteRepository noteRepository)
{
_noteRepo = noteRepository;
}
public IEnumerable<Note> GetNotes(int projectId)
{
return _noteRepo.GetNotes(projectId);
}
}
This would work of course, but I wonder if this is the correct architecture? I couple the simple DTOClass to another Data Access class and possibly also to my DI mechanism (as I need to create an Instance of the Data Access class in the getter of Notes).
Would you do it differently? Is there a better way to do this, also keeping in mind I already use Ninject?
I'm guessing that this is not a POCO or DTO anymore as it now contains logic, but that's okay. I want it to appear like a POCO to outside caller so I like to have a Property "Notes" rather than methods like "GetNotesForProject" on this or other classes.
My current solution is really ugly, as I need to get the Ninject Kernel from my MvcApplication and use it to spin up the ProjectDataProvider class which takes an INoteRepository in it's constructor, to avoid having to put the INoteRepository somewhere in my "DTO"-Class:
public ICollection<Note> Notes
{
get
{
if(_notes == null)
{
var app = HttpContext.Current.ApplicationInstance as MvcApplication;
if (app == null)
throw new InvalidOperationException("Application couldn't be found");
var pdp = app.Kernel.Get<ProjectDataProvider>();
_notes = new List<Note>(pdp.GetNotes(Id));
}
return _notes;
}
}
Edit: Opened a bounty. Let's ignore the terminology of "POCO" and "DTO", I'll refactor accordingly. So this is about: How should the Lazy-Loading code look in such a situation, and can/should I avoid passing INoteRepository into the MyDTOClass?