Search code examples
c#valueinjecter

Where do I add initialisation code in a class library?


I've got a class library that users the ValueInjecter library. In some cases, I need to create custom maps and I'm not sure where I need to put the call(s) to Mapper.AddMap().

If I was using this in an application with a main entry point I could do something like this:

public static void Main(string[] args)
{
    InitialiseMappings();
}

void InitialiseMappings()
{
    Mapper.AddMap<TypeA, TypeB>(src = > { 
        // Mapping code... 
    });

    Mapper.AddMap<TypeC, TypeD>(src = > { 
        // Mapping code... 
    });

    // etc.
}

In a class library, there doesn't appear to be a straightforward way to run 'initialisation' code, so I'm not sure how to approach this. The code can't be called multiple times as trying to add duplicate/identical mappings throws an exception.

Where should I put the code to create these maps?


Solution

  • You can add it in a static constructor.

    public class SomeClass {
        static SomeClass() {
            InitialiseMappings();
        }
    }