A way to have multiple ASP.NET Core Identities per app

Miroslav Makhruk 96 Reputation points
2021-08-24T10:42:22.043+00:00

Hi,
I'm trying to have multiple ASP.NET Core Identities per app.
For example, if I have two controllers "Login" and "Login2", I want one of them to use DB1 as IdentityDbContext while the other to use DB2.

I have these two lines at Startup.ConfigureServices:

services.AddDbContext<IdentityDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DB1")));
services.AddDbContext<IdentityDBContext_v2>(options => options.UseSqlServer(Configuration.GetConnectionString("DB2")));

and this one:

services.AddIdentity<SystemUser, Role>()
 .AddEntityFrameworkStores<IdentityDBContext>() 
 .AddEntityFrameworkStores<IdentityDBContext_v2>() 
 .AddDefaultTokenProviders();

No matter what I do only the first AddEntityFrameworkStores<IdentityDBContext>() works and the DB1 is used in both controllers.
However if I put .AddEntityFrameworkStores<IdentityDBContext_v2>() as the first line then DB2 is used in both controllers.

Microsoft Identity Manager
Microsoft Identity Manager
A family of Microsoft products that manage a user's digital identity using identity synchronization, certificate management, and user provisioning.
610 questions
0 comments No comments
{count} votes

Accepted answer
  1. Miroslav Makhruk 96 Reputation points
    2021-11-09T09:54:14.467+00:00

    Ok, so I've solved it "myself" (all credits to stackoverflow). Finally I've came up with this code:

    services.AddDbContext<IdentityDBContext>((serviceProvider, options) =>
        {
            var httpContext = serviceProvider.GetService<IHttpContextAccessor>().HttpContext;
            var httpRequest = httpContext.Request;
            var pathParts = httpRequest.Path.Value.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
            var pathParsed = decimal.TryParse(pathParts[1], out decimal pathVersion);
            var qsParsed = decimal.TryParse(httpRequest.Query["api-version"], out decimal qsVersion);
            var useV1DB = (!pathParsed || pathVersion == 1) && (!qsParsed || qsVersion == 1);
            options.UseSqlServer(Configuration.GetConnectionString(useV1DB ? "V1DB" : "V2DB"));
      });
    

    it allows me both to have version number as part of the path and as a querystring parameter "api-version"

    0 comments No comments

0 additional answers

Sort by: Most helpful