Suppose that I define two interfaces below:
public interface IReader
{
void Read(string bookName);
}
public interface IWriter
{
void Write(string bookName);
}
Now I want to implement IReader interface like this:
public class Reader : IReader
{
private IEnumerable<string> _books;
public Reader(IEnumerable<string> books)
{
_books = books; // List of books is given through constructor
}
public void Read(string bookName)
{
if (_books.Contains(bookName))
{
// Reading here
}
else
{
throw new InvalidOperationException("Given book name was not found in the library.");
}
}
}
And now I want to define a higher-level class which implements both the two interfaces:
public class Person : IReader, IWriter
{
// This is the data I want to share with IReader argument of constructor
private IList<string> _books = new List<string>();
private IReader _reader;
public Person(IReader reader)
{
_reader = reader; // How do I share books with this object?
}
public void Read(string bookName)
{
_reader.Read(bookName);
}
public void Write(string bookName)
{
_books.Add(bookName);
}
}
As you noticed I used composition to implement the IReader interface. I need to inject an instance of Reader to the Person class but I also need to share my Person's books data with the Reader instance. This is the problem I want to solve.
So far we didn't provide a way to share the list of books with the IReader interface. A few options come to my mind:
First option: Create an IReaderFactory interface and its implementation which creates an instance like this:
public interface IReaderFactory
{
IReader Create(IEnumerable<string> books);
}
public class ReaderFactory : IReaderFactory
{
public IReader Create(IEnumerable<string> books)
{
return new Reader(books);
}
}
This is all good, now I can inject IReaderFactory to my Person constructor instead of IReader. The downside is that it requires 2 extra definitions IReaderFactory, and ReaderFactory.
Second option: Add another method to IReader interface like this:
void Initialize(IEnumreable<string> books);
This works too, in the Person's constructor I can call this method and pass my books to it. But it doesn't seem elegant to me, because now I have to remember calling this method, and this method can be called many times, which is something we don't want.
I don't want to use a DI container and resolve an instance of IReader inside Person's constructor because it hides the dependencies of the Person class.
Now, what is the best way to go in this kind of situation without violating Dependency Inversion Principle ?