Note that there are some explanatory texts on larger screens.

plurals
  1. POHandling exceptions when using dependency injection in C# 4.0
    primarykey
    data
    text
    <p>First of all, please excuse any typo as English is not my native language.</p> <p>Let's say I want to use constructor injection in my application. So for example, I will have something like that:</p> <pre><code>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()); } } </code></pre> <p>If I use constructor injection I have by definition no control nor idea about the concrete instance of the class implementing IDataProvider that will be injected into my DataReader class. Meaning that in my DataReader class I don't know what's going on in GetData method including the fact that I don't know if it may throw an exception or not and if so what kind of exception.</p> <p>In my OutputData method, should I wrap my code into a try { } catch { } block and if so what exception should I catch? If I catch IOException or SQLException or actually <em>any</em> kind of exception means that I am preconceiving some ways IDataProvider may/should be implemented. I don't think it is good. I could also have an XMLDataProvider or NetworkResourceDataProvider injected. But at the same time I must handle exceptions at some point.</p> <p>My question: What is the correct way of handling exception and logging what happens in an application using inversion of control in general and constructor injection more specifically? Also what is the correct way - if any - for throwing exceptions in a class that implements an interface?</p> <p>--</p> <p>Adding a precision to my question, I will not own the code that will implement IDataProvider so I can't even be sure that a custom exception, say <code>DataProviderException</code> will be thrown. Even if I write guidelines for developers to do so...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload