Search code examples
c#dapperdapper-fluentmap

How can you initialize a map in a DAL project?


I've got a simple solution structure of API project, DAL project (Class Library), shared Models project. Inside the DAL project I've created a custom map for one of my POCO's:

internal class AssumptionsMap : EntityMap<Assumptions>
{
    internal AssumptionsMap()
    {
        Map(a => a.Rate).ToColumn("InitialRate");
        Map(a => a.Credit).ToColumn("CredValue");
        Map(a => a.CreditType).ToColumn("CredType");
    }
}

I've created this in the DAL project (Class Library) as this is where it will need to be used in the repository which calls off to get the Assumptions. However, where do I add this:

FluentMapper.Initialize(cfig =>
{
    cfig.AddMap(new AssumptionsMap());
});

My DAL project doesn't have an 'App_Start' as that's in the API project, so how can this map be initialized? I feel like I'm missing something obvious here.

My current attempt is to simply use a static constructor on the QueryStore class I've created that houses all my dapper queries. However, nothing seems to happen when doing this:

public class QueryStore
{
    public const string GetSomething = @"some query";
    // more queries

    static QueryStore()
    {
        FluentMapper.Initialize(cfig =>
        {
            cfig.AddMap(new CommonAssumptionsMap());
        });
    }
}

Solution

  • As this is reusable Class Library project, then there is no place to call this. Class libraries do not have entry point. You have to do a trick.

    Define some InitDal method and put the code in it. Caller must call this method once before start using your data access layer. You need to educate the caller through documentation, help file etc. This help separate initialization/mapping logic from rest of the DAL code.

    Other alternative as you stated in question (UPDATE 2 -- now removed as an attempt to answer) is to use static constructor on one of your class. Choose the class that get instantiated or its static member gets accessed before your mapping comes into the picture.

    A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.