Reputation: 137
Hi I want to check to see if I am overthinking a design issue or not. I am quite new to DI/IoC/TDD so sorry if I am making an obvious mistake.
I have a simple application that will read from a Trade log, read some XML and then save to a database.
Ideally I want to create this application using a TDD approach with DI and possibly IoC.
So I have created some code (see below).
public interface IDataRepository
{
void Save(object someObject);
}
public class DataRepository : IDataRepository
{
public void Save(object someObject){}
}
Public interface ITradeXmlProcessor
{
void ProcessXml;
}
public class TradeXmlProcessor : ITradeXmlProcessor
{
IDataRepository iDataRepository;
public void ProcessXml()
{
// Do work....
SaveTradeData(someObject);
}
private void SaveTradeData(object someObject)
{
iDataRepository = new DataRepository();
iDataRepository.Save(someObject));
}
}
public class ProgramClass
{
ITradeXmlProcessor iTradeXmlProcessor = new TradeXmlProcessor();
iTradeXmlProcessor.ProcessXml();
}
Now to me the issue here is that when I go to test this code I am unable to mock the DataRepository object.
So I considered DI, which looks like :
public class TradeXmlProcessor : ITradeXmlProcessor
{
private IDataRepository _iDataRepository;
public TradeXmlProcessor(IDataRepository iDataRepository)
{
_iDataRepository = iDataRepository;
}
// Use _iDataRepository in process methods.
// ...
}
In my program class I then can pass in a IDataRepository class but is this too much? Is this the correct approach as well? I am a bit worried I might be missing something obvious?
Testability wise I am able to inject a mocked IDataRepository object into a ITradeXMLProcessor class, process it, but not save to the database which is good, but do I really need to mock such a simple operation? I cannot see the benefit I really gain from it?
public class ProgramClass
{
IDataRepository iDataRepository = new DataRepository();
ITradeXmlProcessor iTradeXmlProcessor = new TradeXmlProcessor(iDataRepository);
iTradeXmlProcessor.ProcessXml();
}
Upvotes: 0
Views: 49
Reputation: 28016
Your approach to using DI to inject a service looks absolutely correct.
The question of whether you will get real benefit out of it is a matter of opinion, is not really a question for SO, and requires a lot more context.
Upvotes: 1