Search code examples
c#.netcsvhelper

CsvHelper passing parameter into map constructor when registering class map


I am using CsvHelper to read a csv file and create a list of records from a file.

I have different types of csv files that contain data to be mapped to the same properties of my models but the headers and arrangements of the data in the file may be different. I wanted to write a function that allows the user to map "his" type of csv files to the properties of the model. In the constructor of the Map I am calling another method, to load the custom mapping that the user created

public Map(int accId)
{
    //Load selected model map
    CsvMap csvmap= new();
    csvmap.LoadMapForAccount(accId);
    //Mapping details
    Map(m => m.DateTime).Name(csvmap.DateTimeHeader);
}

The question is how can I pass the parameter int accId if I load the map like this:

csv.Context.RegisterClassMap<Map>();

Solution

  • RegisterClassMap has an overload that takes an instance of ClassMap rather than just a type. Create an instance with the accId to pass in.

    csv.Context.RegisterClassMap(new Map(accId));