I have a CSV file that has among others decimal columns. These columns show values that are in some range. When the value is out of the range it is simply stated as OVR+ or OVR-. In a database, I have chosen a decimal(x, y) type to store these values and since I can not store strings (OVR+/OVR-) in that column I would like to store maximum or minimum values that column can accept (e.g. for a decimal(5,1) it should be 9999.9). Now I know how to handle this - partly. I implement a CustomDecimalConverter class that implements the ITypeConverter interface and that is ok. What I don't know is how can I inject (if possible) a service class into CustomDecimalConverter?
You can add an instance of your CustomDecimalConverter
that already has the service class injected into it.
Either as the default converter
using (var reader = new StringReader("Id,MyDecimal\n1,OVR+"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Context.TypeConverterCache.AddConverter<decimal>(new CustomDecimalConverter(new MyService()));
var records = csv.GetRecords<Foo>().Dump();
}
Or as part of a ClassMap
using (var reader = new StringReader("Id,MyDecimal\n1,OVR+"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Context.RegisterClassMap<FooMap>();
var records = csv.GetRecords<Foo>().Dump();
}
public class FooMap: ClassMap<Foo>
{
public FooMap()
{
Map(x => x.Id);
Map(x => x.MyDecimal).TypeConverter(new CustomDecimalConverter(new MyService()));
}
}