Skip to content

6. Dependency Injection

Jos de Weger edited this page Jan 13, 2019 · 3 revisions

You have the option of creating and configuring a new SheetMapper instance every time you need one, but this might become tedious pretty fast. Newing up an instance everywhere could also decrease testability, so it might be a good idea to use the Dependency Injection Framework of your choice to register SheetToObjects. For projects using Microsoft.Extensions.DependencyInjection, an additional NuGet package called SheetToObjects.Microsoft.Extensions.DependencyInjection is available. When you make use of SheetToObjectConfig's as described here (TODO: create page for SheetToObjectConfig), you can register SheetToObjects and all SheetToObjectConfig's as follows:

serviceCollection.AddSheetToObjects(myAssembly);

This will scan the assembly for SheetToObjectConfig's, adds them to the SheetMapper and registers the SheetMapper as Singleton to the DI container.

There are several overloads for the AddSheetToObjects extension method to specify what assemblies you would like to scan:

  • by specific string that assemblies start with (e.g. "my.name.space"
  • by single assembly
  • by multiple assemblies
  • by single type from assembly, scans the assembly
  • by multiple types from assemblies, scans the assemblies

If you want to register the SheetMapper and configs in one go, you can for instance do the following:

new ServiceCollection().AddSingleton<IMapSheetToObjects>(ctx =>
{
    return new SheetMapper()
        .AddConfigFor<SomeModel>(cfg => cfg
        .AddColumn(column => column
            .Add(column => column.WithHeader("First Name").MapTo(m => m.FirstName))
            .Add(column => column.WithHeader("Last Name").MapTo(m => m.LastName))));
});
Clone this wiki locally