Skip to content

Using Dapper.CX with Dependency Injection

Adam O'Neil edited this page Sep 24, 2020 · 31 revisions

Nuget

Most of the work setting up Dapper.CX for use with dependency injection involves creating components that allow ASP.NET Identity to integrate with your user profile model class in a scalable way. Just about any application you create will require authentication, and you'll have a model class in your application that represents users. What you want to avoid, however, is querying the user profile model from your database with every page view. A more scalable solution is to query user properties once during login, and to capture the profile data as a set of Claims. In turn, Dapper.CX converts these Claims into your user profile model so you have strong-typed access to user profile data at all times. The procedure outlined below describes how to enable your user profile model properties to get this working:

  1. Add a model class to your project that implements IUserBase. Example: UserProfile.

  2. Add NuGet package Dapper.CX.SqlServer.AspNetCore to your project.

  3. Add a service to your project that derives from abstract class DbUserClaimsConverter<TUser>. This used to convert your user profile model class to a set of claims that map onto it. Example: UserProfileClaimsConverter

  4. Add a service to your project that derives from DbUserClaimsFactory<TUser>. Example: UserProfileClaimsFactory. This is used when adding identity during your application startup. This uses the DbUserclaimsFactory<TUser> class you created in step 3, and allows Identity to generate your desired claims when users log in. See example:

services
    .AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddClaimsPrincipalFactory<UserProfileClaimsFactory>();
  1. Use the AddDapperCX extension method in your application startup, like this example:
services.AddDapperCX(
    connectionString, 
    (id) => Convert.ToInt32(id), 
    () => new UserProfileClaimsConverter(connectionString));

The AddDapperCX extension method accepts a database connection string, a delegate that returns your identity column type of choice (-- currently int and long are supported), and lastly a factory that instantiates your DbUserClaimsConverter<TUser> that you created in step 3 above.

Now, you can inject the Dapper.CX SqlServerCrudService<TIdentity, TUser> into your pages or components as per this example.

public class BasePageModel : PageModel
{
    public BasePageModel(DapperCX<int, UserProfile> data)
    {
        Data = data;
    }

    public DapperCX<int, UserProfile> Data { get; }
}

Here, I use a read-only property Data as the accessor for all CRUD operations. The DapperCX class derives from SqlCrudService. Learn more here.

Clone this wiki locally