JoshClose / CsvHelper

Library to help reading and writing CSV files
http://joshclose.github.io/CsvHelper/
Other
4.76k stars 1.07k forks source link

Better support for Dependency Injection #1824

Open GSFatDaemon opened 3 years ago

GSFatDaemon commented 3 years ago

Is your feature request related to a problem? Please describe. CsvWriter only allows the target of the CSV data to be set in the CsvWriter's constructor. This makes injecting the CsvWriter as a parameter to a class's constructor impossible because the point at which the consuming class is constructed is not the point at which we know the filename that we want to write the CSV output to.

Describe the solution you'd like Separate the assignment of the output device (i.e. the TextWriter) from the constructor so that we can inject an IWriter into the consumer's constructor and then assignment the output device later when we know what that output device is.

Describe alternatives you've considered We use the following ICsvHelperFactory to workaround this:-

public interface ICsvHelperFactory
{
    CsvHelper.CsvWriter CreateWriter(TextWriter textWriter);
}

public class CsvHelperFactory : ICsvHelperFactory
{
    public CsvHelper.CsvWriter CreateWriter(TextWriter textWriter)
    {
        return new CsvHelper.CsvWriter(textWriter, CultureInfo.InvariantCulture);
    }
}

We inject an ICsvHelperFactory into our consuming class and call the CreateWriter method when we have the filename that we want to write to.

Additional context None.

JoshClose commented 3 years ago

There would be way too many people that wouldn't use it right if it was done this way.

I believe the factory stuff was created for exactly your usage.

GSFatDaemon commented 3 years ago

Can you point me at some information about the "factory stuff" you are talking about?

JoshClose commented 3 years ago

Ha, I thought you were referring to the factory stuff in CsvHelper, but that's your own thing.

There is CsvHelper.IFactory and CsvHelper.Factory.

firewater commented 3 years ago

@JoshClose : just a mere mortal here wondering if you could please link to some examples of using the "factory stuff". Basically, I'm wondering if I can use CSVHelper with Dependency Injection and, if so, what that would look like. Thanks!

JoshClose commented 3 years ago

@firewater You would just inject an instance of IFactory and that is used to create a reader/writer.

IFactory csvFactory = new Factory(); // This is injected.
using var csvReader = csvFactory.CreateReader(reader, config);