First of all, please excuse any typo, since English is not my first language.
Let's say I want to use constructor injection in my application. So, for example, I will have something like this:
public class FileDataProvider : IDataProvider { public MyData GetData() { // Get data from a file } } public class DatabaseDataProvider : IDataProvider { public MyData GetData() { // Get data from a database } } public class DataReader : IDataReader { private IDataProvider dataProvider; public DataReader(IDataProvider dataProvider) { this.dataProvider = dataProvider; } public void OutputData() { MyData data = dataProvider.GetData(); Console.WriteLine("{0}", data.ToString()); } }
If I use constructor injection, by definition I do not control and do not represent a specific instance of the class that implements IDataProvider, which will be introduced into my DataReader class. This means that in my DataReader class, I donβt know what is going on in the GetData method, including the fact that I donβt know if it can throw an exception or not, and if so, which exception.
In my OutputData method, I have to wrap my code in a try {} catch {} block, and if so, what exception should I catch? If I catch an IOException or SQLException or actually some exception, then I anticipate some of the ways that IDataProvider can / should be implemented. I do not think this is good. I could also use XMLDataProvider or NetworkResourceDataProvider. But at the same time, I have to handle exceptions at some point.
My question is: What is the correct way to handle exceptions and register what is happening in the application, using inversion of control in general and installing the constructor more specifically? And what is the right way - if any - to throw exceptions in the class that implements the interface?
-
Adding accuracy to my question, I will not have code that will implement IDataProvider, so I canβt even be sure that a custom exception will be thrown, such as a DataProviderException . Even if I write recommendations for developers to do this ...