├── .gitattributes ├── .gitignore ├── multiTenantApp.sln └── multiTenantApp ├── Controllers ├── ProductsController.cs └── TenantsController.cs ├── Middleware └── TenantResolver.cs ├── Models ├── IMustHaveTenant.cs ├── Product.cs └── Tenant.cs ├── Persistence ├── Contexts │ ├── ApplicationDbContext.cs │ ├── BaseDbContext.cs │ └── BaseDbContextFactory.cs ├── Extensions │ └── DatabaseInitializationExtensions.cs └── Migrations │ ├── AppDb │ ├── 20240829160916_Initial.Designer.cs │ ├── 20240829160916_Initial.cs │ └── ApplicationDbContextModelSnapshot.cs │ └── BaseDb │ ├── 20240829160705_Initial.Designer.cs │ ├── 20240829160705_Initial.cs │ └── BaseDbContextModelSnapshot.cs ├── Program.cs ├── Properties ├── ServiceDependencies │ ├── MultiTenantApp - Web Deploy │ │ ├── mssql1.arm.json │ │ └── profile.arm.json │ └── MultiTenantApp - Zip Deploy │ │ └── profile.arm.json ├── launchSettings.json ├── serviceDependencies.MultiTenantApp - Web Deploy.json └── serviceDependencies.json ├── Services ├── CurrentTenantService.cs ├── ICurrentTenantService.cs ├── ProductService │ ├── DTOs │ │ └── CreateProductRequest.cs │ ├── IProductService.cs │ └── ProductService.cs └── TenantService │ ├── DTOs │ └── CreateTenantRequest.cs │ ├── ITenantService.cs │ └── TenantService.cs ├── appsettings.Development.json ├── appsettings.json └── multiTenantApp.csproj /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /multiTenantApp.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.4.33122.133 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "multiTenantApp", "multiTenantApp\multiTenantApp.csproj", "{849F17C2-32F4-44AC-BE52-9CB3FB47572D}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {849F17C2-32F4-44AC-BE52-9CB3FB47572D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {849F17C2-32F4-44AC-BE52-9CB3FB47572D}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {849F17C2-32F4-44AC-BE52-9CB3FB47572D}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {849F17C2-32F4-44AC-BE52-9CB3FB47572D}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {BD5B2110-CEB6-42DD-9B2B-79B3C93CD364} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /multiTenantApp/Controllers/ProductsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using multiTenantApp.Services.ProductService; 3 | using multiTenantApp.Services.ProductService.DTOs; 4 | 5 | namespace queryFilterApp.Controllers 6 | { 7 | [Route("api/[controller]")] 8 | [ApiController] 9 | public class ProductsController : ControllerBase 10 | { 11 | private readonly IProductService _productService; 12 | 13 | public ProductsController(IProductService productService) 14 | { 15 | _productService = productService; // inject the products service 16 | } 17 | 18 | // Get list of products 19 | [HttpGet] 20 | public IActionResult Get() 21 | { 22 | var list = _productService.GetAllProducts(); 23 | return Ok(list); 24 | } 25 | 26 | // Create a new product 27 | [HttpPost] 28 | public IActionResult Post(CreateProductRequest request) 29 | { 30 | var result = _productService.CreateProduct(request); 31 | return Ok(result); 32 | } 33 | 34 | // Delete a product by id 35 | [HttpDelete("{id}")] 36 | public IActionResult Delete(int id) 37 | { 38 | var result = _productService.DeleteProduct(id); 39 | return Ok(result); 40 | } 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /multiTenantApp/Controllers/TenantsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using multiTenantApp.Services.TenantService; 3 | using multiTenantApp.Services.TenantService.DTOs; 4 | 5 | namespace multiTenantApp.Controllers 6 | { 7 | [Route("api/[controller]")] 8 | [ApiController] 9 | public class TenantsController : ControllerBase 10 | { 11 | private readonly ITenantService _tenantService; 12 | 13 | public TenantsController(ITenantService tenantService) 14 | { 15 | _tenantService = tenantService; 16 | } 17 | 18 | // Create a new tenant 19 | [HttpPost] 20 | public IActionResult Post(CreateTenantRequest request) 21 | { 22 | var result = _tenantService.CreateTenant(request); 23 | return Ok(result); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /multiTenantApp/Middleware/TenantResolver.cs: -------------------------------------------------------------------------------- 1 | using multiTenantApp.Services; 2 | 3 | namespace multiTenantApp.Middleware 4 | { 5 | public class TenantResolver 6 | { 7 | private readonly RequestDelegate _next; 8 | public TenantResolver(RequestDelegate next) 9 | { 10 | _next = next; 11 | } 12 | 13 | // Get Tenant Id from incoming requests 14 | public async Task InvokeAsync(HttpContext context, ICurrentTenantService currentTenantService) 15 | { 16 | context.Request.Headers.TryGetValue("tenant", out var tenantFromHeader); // Tenant Id from incoming request header 17 | if (string.IsNullOrEmpty(tenantFromHeader) == false) 18 | { 19 | await currentTenantService.SetTenant(tenantFromHeader); 20 | } 21 | 22 | await _next(context); 23 | } 24 | 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /multiTenantApp/Models/IMustHaveTenant.cs: -------------------------------------------------------------------------------- 1 | namespace multiTenantApp.Models 2 | { 3 | public interface IMustHaveTenant 4 | { 5 | public string TenantId { get; set; } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /multiTenantApp/Models/Product.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace multiTenantApp.Models 3 | { 4 | // sample business entity 5 | public class Product : IMustHaveTenant 6 | { 7 | public int Id { get; set; } 8 | public string Name { get; set; } 9 | public string TenantId { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /multiTenantApp/Models/Tenant.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations.Schema; 2 | using System.ComponentModel.DataAnnotations; 3 | 4 | namespace multiTenantApp.Models 5 | { 6 | public class Tenant 7 | { 8 | [Key] 9 | [DatabaseGenerated(DatabaseGeneratedOption.None)] 10 | public string Id { get; set; } 11 | public string Name { get; set; } 12 | public string? ConnectionString { get; set; } 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /multiTenantApp/Persistence/Contexts/ApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using multiTenantApp.Models; 3 | using multiTenantApp.Services; 4 | 5 | namespace multiTenantApp.Persistence.Contexts 6 | { 7 | // in a multi-database scenerio, this context manages tables that are generated in every database 8 | 9 | //---------------------------------- CLI COMMANDS -------------------------------------------------- 10 | 11 | // when scaffolding database migrations, you must specify which context (ApplicationDbContext), -o is the output directory, use the following command: 12 | 13 | // add-migration -Context ApplicationDbContext -o Persistence/Migrations/AppDb MigrationName 14 | // update-database -Context ApplicationDbContext 15 | 16 | //-------------------------------------------------------------------------------------------------- 17 | 18 | public class ApplicationDbContext : DbContext 19 | { 20 | private readonly ICurrentTenantService _currentTenantService; 21 | public string CurrentTenantId { get; set; } 22 | public string CurrentTenantConnectionString { get; set; } 23 | 24 | 25 | // Constructor 26 | public ApplicationDbContext(ICurrentTenantService currentTenantService, DbContextOptions options) : base(options) 27 | { 28 | _currentTenantService = currentTenantService; 29 | CurrentTenantId = _currentTenantService.TenantId; 30 | CurrentTenantConnectionString = _currentTenantService.ConnectionString; 31 | 32 | } 33 | 34 | // Application DbSets -- create for entity types to be applied to all databases 35 | public DbSet Products { get; set; } 36 | 37 | // On Model Creating - multitenancy query filter, fires once on app start 38 | protected override void OnModelCreating(ModelBuilder builder) 39 | { 40 | builder.Entity().HasQueryFilter(a => a.TenantId == CurrentTenantId); 41 | } 42 | 43 | // On Configuring -- dynamic connection string, fires on every request 44 | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 45 | { 46 | string tenantConnectionString = CurrentTenantConnectionString; 47 | if (!string.IsNullOrEmpty(tenantConnectionString)) // use tenant db if one is specified 48 | { 49 | _ = optionsBuilder.UseSqlServer(tenantConnectionString); 50 | } 51 | } 52 | 53 | 54 | // On Save Changes - write tenant Id to table 55 | public override int SaveChanges() 56 | { 57 | foreach (var entry in ChangeTracker.Entries().ToList()) 58 | { 59 | switch (entry.State) 60 | { 61 | case EntityState.Added: 62 | case EntityState.Modified: 63 | entry.Entity.TenantId = CurrentTenantId; 64 | break; 65 | } 66 | } 67 | var result = base.SaveChanges(); 68 | return result; 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /multiTenantApp/Persistence/Contexts/BaseDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using multiTenantApp.Models; 3 | 4 | namespace multiTenantApp.Persistence.Contexts 5 | { 6 | // in a multi-database scenerio, this context manages tables that are generated in only the main database 7 | 8 | //---------------------------------- CLI COMMANDS -------------------------------------------------- 9 | 10 | // when scaffolding database migrations, you must specify which context (BaseDbContext), -o is the output directory, use the following command: 11 | 12 | // add-migration -Context BaseDbContext -o Persistence/Migrations/BaseDb MigrationName 13 | // update-database -Context BaseDbContext 14 | 15 | 16 | //-------------------------------------------------------------------------------------------------- 17 | 18 | public class BaseDbContext : DbContext 19 | { 20 | public BaseDbContext(DbContextOptions options) 21 | : base(options) 22 | { 23 | } 24 | 25 | public DbSet Tenants { get; set; } 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /multiTenantApp/Persistence/Contexts/BaseDbContextFactory.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Design; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace multiTenantApp.Persistence.Contexts 5 | { 6 | public class BaseDbContextFactory : IDesignTimeDbContextFactory 7 | { 8 | public BaseDbContext CreateDbContext(string[] args) // neccessary for EF migration designer to run on this context 9 | { 10 | 11 | // Build the configuration by reading from the appsettings.json file (requires Microsoft.Extensions.Configuration.Json Nuget Package) 12 | IConfigurationRoot configuration = new ConfigurationBuilder() 13 | .SetBasePath(Directory.GetCurrentDirectory()) 14 | .AddJsonFile("appsettings.json") 15 | .Build(); 16 | 17 | // Retrieve the connection string from the configuration 18 | string connectionString = configuration.GetConnectionString("DefaultConnection"); 19 | 20 | 21 | DbContextOptionsBuilder optionsBuilder = new(); 22 | _ = optionsBuilder.UseSqlServer(connectionString); 23 | return new BaseDbContext(optionsBuilder.Options); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /multiTenantApp/Persistence/Extensions/DatabaseInitializationExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using multiTenantApp.Models; 3 | using multiTenantApp.Persistence.Contexts; 4 | 5 | namespace multiTenantApp.Persistence.Extensions 6 | { 7 | public static class DatabaseInitializationExtensions // renamed from MultipleDatabaseExtentions in video 8 | { 9 | public static IServiceCollection AddAndMigrateTenantDatabases(this IServiceCollection services, IConfiguration configuration) 10 | { 11 | 12 | // Base Context (central db) - get a list of tenants 13 | using IServiceScope scopeTenant = services.BuildServiceProvider().CreateScope(); 14 | BaseDbContext baseDbContext = scopeTenant.ServiceProvider.GetRequiredService(); 15 | 16 | if (baseDbContext.Database.GetPendingMigrations().Any()) 17 | { 18 | Console.ForegroundColor = ConsoleColor.Blue; 19 | Console.WriteLine("Applying BaseDb Migrations."); 20 | Console.ResetColor(); 21 | baseDbContext.Database.Migrate(); // apply migrations on baseDbContext 22 | } 23 | 24 | 25 | List tenantsInDb = baseDbContext.Tenants.ToList(); 26 | 27 | string defaultConnectionString = configuration.GetConnectionString("DefaultConnection"); // read default connection string from appsettings.json 28 | 29 | foreach (Tenant tenant in tenantsInDb) 30 | { 31 | string connectionString = string.IsNullOrEmpty(tenant.ConnectionString) ? defaultConnectionString : tenant.ConnectionString; 32 | 33 | // Application Db Context (app - per tenant) 34 | using IServiceScope scopeApplication = services.BuildServiceProvider().CreateScope(); 35 | ApplicationDbContext dbContext = scopeApplication.ServiceProvider.GetRequiredService(); 36 | dbContext.Database.SetConnectionString(connectionString); 37 | if (dbContext.Database.GetPendingMigrations().Any()) 38 | { 39 | Console.ForegroundColor = ConsoleColor.Blue; 40 | Console.WriteLine($"Applying Migrations for '{tenant.Id}' tenant."); 41 | Console.ResetColor(); 42 | dbContext.Database.Migrate(); 43 | } 44 | } 45 | 46 | return services; 47 | } 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /multiTenantApp/Persistence/Migrations/AppDb/20240829160916_Initial.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using multiTenantApp.Persistence.Contexts; 8 | 9 | #nullable disable 10 | 11 | namespace multiTenantApp.Persistence.Migrations.AppDb 12 | { 13 | [DbContext(typeof(ApplicationDbContext))] 14 | [Migration("20240829160916_Initial")] 15 | partial class Initial 16 | { 17 | /// 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "8.0.0") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 24 | 25 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); 26 | 27 | modelBuilder.Entity("multiTenantApp.Models.Product", b => 28 | { 29 | b.Property("Id") 30 | .ValueGeneratedOnAdd() 31 | .HasColumnType("int"); 32 | 33 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); 34 | 35 | b.Property("Name") 36 | .IsRequired() 37 | .HasColumnType("nvarchar(max)"); 38 | 39 | b.Property("TenantId") 40 | .IsRequired() 41 | .HasColumnType("nvarchar(max)"); 42 | 43 | b.HasKey("Id"); 44 | 45 | b.ToTable("Products"); 46 | }); 47 | #pragma warning restore 612, 618 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /multiTenantApp/Persistence/Migrations/AppDb/20240829160916_Initial.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | namespace multiTenantApp.Persistence.Migrations.AppDb 6 | { 7 | /// 8 | public partial class Initial : Migration 9 | { 10 | /// 11 | protected override void Up(MigrationBuilder migrationBuilder) 12 | { 13 | migrationBuilder.CreateTable( 14 | name: "Products", 15 | columns: table => new 16 | { 17 | Id = table.Column(type: "int", nullable: false) 18 | .Annotation("SqlServer:Identity", "1, 1"), 19 | Name = table.Column(type: "nvarchar(max)", nullable: false), 20 | TenantId = table.Column(type: "nvarchar(max)", nullable: false) 21 | }, 22 | constraints: table => 23 | { 24 | table.PrimaryKey("PK_Products", x => x.Id); 25 | }); 26 | } 27 | 28 | /// 29 | protected override void Down(MigrationBuilder migrationBuilder) 30 | { 31 | migrationBuilder.DropTable( 32 | name: "Products"); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /multiTenantApp/Persistence/Migrations/AppDb/ApplicationDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 6 | using multiTenantApp.Persistence.Contexts; 7 | 8 | #nullable disable 9 | 10 | namespace multiTenantApp.Persistence.Migrations.AppDb 11 | { 12 | [DbContext(typeof(ApplicationDbContext))] 13 | partial class ApplicationDbContextModelSnapshot : ModelSnapshot 14 | { 15 | protected override void BuildModel(ModelBuilder modelBuilder) 16 | { 17 | #pragma warning disable 612, 618 18 | modelBuilder 19 | .HasAnnotation("ProductVersion", "8.0.0") 20 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 21 | 22 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); 23 | 24 | modelBuilder.Entity("multiTenantApp.Models.Product", b => 25 | { 26 | b.Property("Id") 27 | .ValueGeneratedOnAdd() 28 | .HasColumnType("int"); 29 | 30 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); 31 | 32 | b.Property("Name") 33 | .IsRequired() 34 | .HasColumnType("nvarchar(max)"); 35 | 36 | b.Property("TenantId") 37 | .IsRequired() 38 | .HasColumnType("nvarchar(max)"); 39 | 40 | b.HasKey("Id"); 41 | 42 | b.ToTable("Products"); 43 | }); 44 | #pragma warning restore 612, 618 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /multiTenantApp/Persistence/Migrations/BaseDb/20240829160705_Initial.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using multiTenantApp.Persistence.Contexts; 8 | 9 | #nullable disable 10 | 11 | namespace multiTenantApp.Persistence.Migrations.BaseDb 12 | { 13 | [DbContext(typeof(BaseDbContext))] 14 | [Migration("20240829160705_Initial")] 15 | partial class Initial 16 | { 17 | /// 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "8.0.0") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 24 | 25 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); 26 | 27 | modelBuilder.Entity("multiTenantApp.Models.Tenant", b => 28 | { 29 | b.Property("Id") 30 | .HasColumnType("nvarchar(450)"); 31 | 32 | b.Property("ConnectionString") 33 | .HasColumnType("nvarchar(max)"); 34 | 35 | b.Property("Name") 36 | .IsRequired() 37 | .HasColumnType("nvarchar(max)"); 38 | 39 | b.HasKey("Id"); 40 | 41 | b.ToTable("Tenants"); 42 | }); 43 | #pragma warning restore 612, 618 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /multiTenantApp/Persistence/Migrations/BaseDb/20240829160705_Initial.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | namespace multiTenantApp.Persistence.Migrations.BaseDb 6 | { 7 | /// 8 | public partial class Initial : Migration 9 | { 10 | /// 11 | protected override void Up(MigrationBuilder migrationBuilder) 12 | { 13 | migrationBuilder.CreateTable( 14 | name: "Tenants", 15 | columns: table => new 16 | { 17 | Id = table.Column(type: "nvarchar(450)", nullable: false), 18 | Name = table.Column(type: "nvarchar(max)", nullable: false), 19 | ConnectionString = table.Column(type: "nvarchar(max)", nullable: true) 20 | }, 21 | constraints: table => 22 | { 23 | table.PrimaryKey("PK_Tenants", x => x.Id); 24 | }); 25 | } 26 | 27 | /// 28 | protected override void Down(MigrationBuilder migrationBuilder) 29 | { 30 | migrationBuilder.DropTable( 31 | name: "Tenants"); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /multiTenantApp/Persistence/Migrations/BaseDb/BaseDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 6 | using multiTenantApp.Persistence.Contexts; 7 | 8 | #nullable disable 9 | 10 | namespace multiTenantApp.Persistence.Migrations.BaseDb 11 | { 12 | [DbContext(typeof(BaseDbContext))] 13 | partial class BaseDbContextModelSnapshot : ModelSnapshot 14 | { 15 | protected override void BuildModel(ModelBuilder modelBuilder) 16 | { 17 | #pragma warning disable 612, 618 18 | modelBuilder 19 | .HasAnnotation("ProductVersion", "8.0.0") 20 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 21 | 22 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); 23 | 24 | modelBuilder.Entity("multiTenantApp.Models.Tenant", b => 25 | { 26 | b.Property("Id") 27 | .HasColumnType("nvarchar(450)"); 28 | 29 | b.Property("ConnectionString") 30 | .HasColumnType("nvarchar(max)"); 31 | 32 | b.Property("Name") 33 | .IsRequired() 34 | .HasColumnType("nvarchar(max)"); 35 | 36 | b.HasKey("Id"); 37 | 38 | b.ToTable("Tenants"); 39 | }); 40 | #pragma warning restore 612, 618 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /multiTenantApp/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using multiTenantApp.Middleware; 3 | using multiTenantApp.Persistence.Contexts; 4 | using multiTenantApp.Persistence.Extensions; 5 | using multiTenantApp.Services; 6 | using multiTenantApp.Services.ProductService; 7 | using multiTenantApp.Services.TenantService; 8 | 9 | // NOTE: In this simple example app there is no seed method, 10 | // so be sure to create a tenant before trying to create a product (use the create tenant endpoint) 11 | 12 | var builder = WebApplication.CreateBuilder(args); 13 | 14 | // Add services to the container. 15 | builder.Services.AddControllers(); 16 | builder.Services.AddEndpointsApiExplorer(); 17 | 18 | // Current tenant service with scoped lifetime (created per each request) 19 | builder.Services.AddScoped(); 20 | 21 | // adding a database service with configuration -- connection string read from appsettings.json 22 | builder.Services.AddDbContext(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); 23 | builder.Services.AddDbContext(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); 24 | builder.Services.AddAndMigrateTenantDatabases(builder.Configuration); 25 | 26 | // CRUD services with transient lifetime 27 | builder.Services.AddTransient(); 28 | builder.Services.AddTransient(); 29 | 30 | var app = builder.Build(); 31 | 32 | app.UseHttpsRedirection(); 33 | app.UseAuthorization(); 34 | app.UseMiddleware(); 35 | app.MapControllers(); 36 | 37 | app.Run(); 38 | -------------------------------------------------------------------------------- /multiTenantApp/Properties/ServiceDependencies/MultiTenantApp - Web Deploy/mssql1.arm.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#", 3 | "contentVersion": "1.0.0.0", 4 | "parameters": { 5 | "resourceGroupName": { 6 | "type": "string", 7 | "defaultValue": "NanoGroup", 8 | "metadata": { 9 | "_parameterType": "resourceGroup", 10 | "description": "Name of the resource group for the resource. It is recommended to put resources under same resource group for better tracking." 11 | } 12 | }, 13 | "resourceGroupLocation": { 14 | "type": "string", 15 | "defaultValue": "centralus", 16 | "metadata": { 17 | "_parameterType": "location", 18 | "description": "Location of the resource group. Resource groups could have different location than resources." 19 | } 20 | }, 21 | "resourceLocation": { 22 | "type": "string", 23 | "defaultValue": "[parameters('resourceGroupLocation')]", 24 | "metadata": { 25 | "_parameterType": "location", 26 | "description": "Location of the resource. By default use resource group's location, unless the resource provider is not supported there." 27 | } 28 | } 29 | }, 30 | "resources": [ 31 | { 32 | "type": "Microsoft.Resources/resourceGroups", 33 | "name": "[parameters('resourceGroupName')]", 34 | "location": "[parameters('resourceGroupLocation')]", 35 | "apiVersion": "2019-10-01" 36 | }, 37 | { 38 | "type": "Microsoft.Resources/deployments", 39 | "name": "[concat(parameters('resourceGroupName'), 'Deployment', uniqueString(concat('MultiTenantAppDb', subscription().subscriptionId)))]", 40 | "resourceGroup": "[parameters('resourceGroupName')]", 41 | "apiVersion": "2019-10-01", 42 | "dependsOn": [ 43 | "[parameters('resourceGroupName')]" 44 | ], 45 | "properties": { 46 | "mode": "Incremental", 47 | "template": { 48 | "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", 49 | "contentVersion": "1.0.0.0", 50 | "resources": [ 51 | { 52 | "kind": "v12.0", 53 | "location": "[parameters('resourceLocation')]", 54 | "name": "aspnano", 55 | "type": "Microsoft.Sql/servers", 56 | "apiVersion": "2017-10-01-preview" 57 | }, 58 | { 59 | "sku": { 60 | "name": "ElasticPool", 61 | "tier": "Basic", 62 | "capacity": 0 63 | }, 64 | "kind": "v12.0,user,pool", 65 | "location": "[parameters('resourceLocation')]", 66 | "name": "aspnano/MultiTenantAppDb", 67 | "type": "Microsoft.Sql/servers/databases", 68 | "apiVersion": "2017-10-01-preview", 69 | "dependsOn": [ 70 | "aspnano" 71 | ] 72 | } 73 | ] 74 | } 75 | } 76 | } 77 | ], 78 | "metadata": { 79 | "_dependencyType": "mssql.azure" 80 | } 81 | } -------------------------------------------------------------------------------- /multiTenantApp/Properties/ServiceDependencies/MultiTenantApp - Web Deploy/profile.arm.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#", 3 | "contentVersion": "1.0.0.0", 4 | "metadata": { 5 | "_dependencyType": "compute.appService.windows" 6 | }, 7 | "parameters": { 8 | "resourceGroupName": { 9 | "type": "string", 10 | "defaultValue": "NanoGroup", 11 | "metadata": { 12 | "description": "Name of the resource group for the resource. It is recommended to put resources under same resource group for better tracking." 13 | } 14 | }, 15 | "resourceGroupLocation": { 16 | "type": "string", 17 | "defaultValue": "centralus", 18 | "metadata": { 19 | "description": "Location of the resource group. Resource groups could have different location than resources, however by default we use API versions from latest hybrid profile which support all locations for resource types we support." 20 | } 21 | }, 22 | "resourceName": { 23 | "type": "string", 24 | "defaultValue": "MultiTenantApp", 25 | "metadata": { 26 | "description": "Name of the main resource to be created by this template." 27 | } 28 | }, 29 | "resourceLocation": { 30 | "type": "string", 31 | "defaultValue": "[parameters('resourceGroupLocation')]", 32 | "metadata": { 33 | "description": "Location of the resource. By default use resource group's location, unless the resource provider is not supported there." 34 | } 35 | } 36 | }, 37 | "variables": { 38 | "appServicePlan_name": "[concat('Plan', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]", 39 | "appServicePlan_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Web/serverFarms/', variables('appServicePlan_name'))]" 40 | }, 41 | "resources": [ 42 | { 43 | "type": "Microsoft.Resources/resourceGroups", 44 | "name": "[parameters('resourceGroupName')]", 45 | "location": "[parameters('resourceGroupLocation')]", 46 | "apiVersion": "2019-10-01" 47 | }, 48 | { 49 | "type": "Microsoft.Resources/deployments", 50 | "name": "[concat(parameters('resourceGroupName'), 'Deployment', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]", 51 | "resourceGroup": "[parameters('resourceGroupName')]", 52 | "apiVersion": "2019-10-01", 53 | "dependsOn": [ 54 | "[parameters('resourceGroupName')]" 55 | ], 56 | "properties": { 57 | "mode": "Incremental", 58 | "template": { 59 | "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", 60 | "contentVersion": "1.0.0.0", 61 | "resources": [ 62 | { 63 | "location": "[parameters('resourceLocation')]", 64 | "name": "[parameters('resourceName')]", 65 | "type": "Microsoft.Web/sites", 66 | "apiVersion": "2015-08-01", 67 | "tags": { 68 | "[concat('hidden-related:', variables('appServicePlan_ResourceId'))]": "empty" 69 | }, 70 | "dependsOn": [ 71 | "[variables('appServicePlan_ResourceId')]" 72 | ], 73 | "kind": "app", 74 | "properties": { 75 | "name": "[parameters('resourceName')]", 76 | "kind": "app", 77 | "httpsOnly": true, 78 | "reserved": false, 79 | "serverFarmId": "[variables('appServicePlan_ResourceId')]", 80 | "siteConfig": { 81 | "metadata": [ 82 | { 83 | "name": "CURRENT_STACK", 84 | "value": "dotnetcore" 85 | } 86 | ] 87 | } 88 | }, 89 | "identity": { 90 | "type": "SystemAssigned" 91 | } 92 | }, 93 | { 94 | "location": "[parameters('resourceLocation')]", 95 | "name": "[variables('appServicePlan_name')]", 96 | "type": "Microsoft.Web/serverFarms", 97 | "apiVersion": "2015-08-01", 98 | "sku": { 99 | "name": "S1", 100 | "tier": "Standard", 101 | "family": "S", 102 | "size": "S1" 103 | }, 104 | "properties": { 105 | "name": "[variables('appServicePlan_name')]" 106 | } 107 | } 108 | ] 109 | } 110 | } 111 | } 112 | ] 113 | } -------------------------------------------------------------------------------- /multiTenantApp/Properties/ServiceDependencies/MultiTenantApp - Zip Deploy/profile.arm.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#", 3 | "contentVersion": "1.0.0.0", 4 | "metadata": { 5 | "_dependencyType": "compute.function.windows.appService" 6 | }, 7 | "parameters": { 8 | "resourceGroupName": { 9 | "type": "string", 10 | "defaultValue": "NanoGroup", 11 | "metadata": { 12 | "description": "Name of the resource group for the resource. It is recommended to put resources under same resource group for better tracking." 13 | } 14 | }, 15 | "resourceGroupLocation": { 16 | "type": "string", 17 | "defaultValue": "centralus", 18 | "metadata": { 19 | "description": "Location of the resource group. Resource groups could have different location than resources, however by default we use API versions from latest hybrid profile which support all locations for resource types we support." 20 | } 21 | }, 22 | "resourceName": { 23 | "type": "string", 24 | "defaultValue": "MultiTenantApp", 25 | "metadata": { 26 | "description": "Name of the main resource to be created by this template." 27 | } 28 | }, 29 | "resourceLocation": { 30 | "type": "string", 31 | "defaultValue": "[parameters('resourceGroupLocation')]", 32 | "metadata": { 33 | "description": "Location of the resource. By default use resource group's location, unless the resource provider is not supported there." 34 | } 35 | } 36 | }, 37 | "resources": [ 38 | { 39 | "type": "Microsoft.Resources/resourceGroups", 40 | "name": "[parameters('resourceGroupName')]", 41 | "location": "[parameters('resourceGroupLocation')]", 42 | "apiVersion": "2019-10-01" 43 | }, 44 | { 45 | "type": "Microsoft.Resources/deployments", 46 | "name": "[concat(parameters('resourceGroupName'), 'Deployment', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]", 47 | "resourceGroup": "[parameters('resourceGroupName')]", 48 | "apiVersion": "2019-10-01", 49 | "dependsOn": [ 50 | "[parameters('resourceGroupName')]" 51 | ], 52 | "properties": { 53 | "mode": "Incremental", 54 | "expressionEvaluationOptions": { 55 | "scope": "inner" 56 | }, 57 | "parameters": { 58 | "resourceGroupName": { 59 | "value": "[parameters('resourceGroupName')]" 60 | }, 61 | "resourceGroupLocation": { 62 | "value": "[parameters('resourceGroupLocation')]" 63 | }, 64 | "resourceName": { 65 | "value": "[parameters('resourceName')]" 66 | }, 67 | "resourceLocation": { 68 | "value": "[parameters('resourceLocation')]" 69 | } 70 | }, 71 | "template": { 72 | "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", 73 | "contentVersion": "1.0.0.0", 74 | "parameters": { 75 | "resourceGroupName": { 76 | "type": "string" 77 | }, 78 | "resourceGroupLocation": { 79 | "type": "string" 80 | }, 81 | "resourceName": { 82 | "type": "string" 83 | }, 84 | "resourceLocation": { 85 | "type": "string" 86 | } 87 | }, 88 | "variables": { 89 | "storage_name": "[toLower(concat('storage', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId))))]", 90 | "appServicePlan_name": "[concat('Plan', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]", 91 | "storage_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Storage/storageAccounts/', variables('storage_name'))]", 92 | "appServicePlan_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Web/serverFarms/', variables('appServicePlan_name'))]", 93 | "function_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Web/sites/', parameters('resourceName'))]" 94 | }, 95 | "resources": [ 96 | { 97 | "location": "[parameters('resourceLocation')]", 98 | "name": "[parameters('resourceName')]", 99 | "type": "Microsoft.Web/sites", 100 | "apiVersion": "2015-08-01", 101 | "tags": { 102 | "[concat('hidden-related:', variables('appServicePlan_ResourceId'))]": "empty" 103 | }, 104 | "dependsOn": [ 105 | "[variables('appServicePlan_ResourceId')]", 106 | "[variables('storage_ResourceId')]" 107 | ], 108 | "kind": "functionapp", 109 | "properties": { 110 | "name": "[parameters('resourceName')]", 111 | "kind": "functionapp", 112 | "httpsOnly": true, 113 | "reserved": false, 114 | "serverFarmId": "[variables('appServicePlan_ResourceId')]", 115 | "siteConfig": { 116 | "alwaysOn": true 117 | } 118 | }, 119 | "identity": { 120 | "type": "SystemAssigned" 121 | }, 122 | "resources": [ 123 | { 124 | "name": "appsettings", 125 | "type": "config", 126 | "apiVersion": "2015-08-01", 127 | "dependsOn": [ 128 | "[variables('function_ResourceId')]" 129 | ], 130 | "properties": { 131 | "AzureWebJobsStorage": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storage_name'), ';AccountKey=', listKeys(variables('storage_ResourceId'), '2017-10-01').keys[0].value, ';EndpointSuffix=', 'core.windows.net')]", 132 | "FUNCTIONS_EXTENSION_VERSION": "~3", 133 | "FUNCTIONS_WORKER_RUNTIME": "dotnet" 134 | } 135 | } 136 | ] 137 | }, 138 | { 139 | "location": "[parameters('resourceGroupLocation')]", 140 | "name": "[variables('storage_name')]", 141 | "type": "Microsoft.Storage/storageAccounts", 142 | "apiVersion": "2017-10-01", 143 | "tags": { 144 | "[concat('hidden-related:', concat('/providers/Microsoft.Web/sites/', parameters('resourceName')))]": "empty" 145 | }, 146 | "properties": { 147 | "supportsHttpsTrafficOnly": true 148 | }, 149 | "sku": { 150 | "name": "Standard_LRS" 151 | }, 152 | "kind": "Storage" 153 | }, 154 | { 155 | "location": "[parameters('resourceGroupLocation')]", 156 | "name": "[variables('appServicePlan_name')]", 157 | "type": "Microsoft.Web/serverFarms", 158 | "apiVersion": "2015-08-01", 159 | "sku": { 160 | "name": "S1", 161 | "tier": "Standard", 162 | "family": "S", 163 | "size": "S1" 164 | }, 165 | "properties": { 166 | "name": "[variables('appServicePlan_name')]" 167 | } 168 | } 169 | ] 170 | } 171 | } 172 | } 173 | ] 174 | } -------------------------------------------------------------------------------- /multiTenantApp/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:37918", 8 | "sslPort": 44397 9 | } 10 | }, 11 | "profiles": { 12 | "http": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "http://localhost:5284", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "https": { 23 | "commandName": "Project", 24 | "dotnetRunMessages": true, 25 | "launchBrowser": true, 26 | "launchUrl": "swagger", 27 | "applicationUrl": "https://localhost:7015;http://localhost:5284", 28 | "environmentVariables": { 29 | "ASPNETCORE_ENVIRONMENT": "Development" 30 | } 31 | }, 32 | "IIS Express": { 33 | "commandName": "IISExpress", 34 | "launchBrowser": true, 35 | "launchUrl": "swagger", 36 | "environmentVariables": { 37 | "ASPNETCORE_ENVIRONMENT": "Development" 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /multiTenantApp/Properties/serviceDependencies.MultiTenantApp - Web Deploy.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "mssql1": { 4 | "serviceConnectorResourceId": "/subscriptions/[parameters('subscriptionId')]/resourceGroups/[parameters('resourceGroupName')]/providers/Microsoft.Web/sites/MultiTenantApp/providers/Microsoft.ServiceLinker/linkers/ConnectionStringsDefaultConnection_DF02F96204", 5 | "secretStore": "AzureAppSettings", 6 | "resourceId": "/subscriptions/[parameters('subscriptionId')]/resourceGroups/[parameters('resourceGroupName')]/providers/Microsoft.Sql/servers/aspnano/databases/MultiTenantAppDb", 7 | "type": "mssql.azure", 8 | "connectionId": "ConnectionStrings:DefaultConnection", 9 | "dynamicId": null 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /multiTenantApp/Properties/serviceDependencies.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "mssql1": { 4 | "type": "mssql", 5 | "connectionId": "ConnectionStrings:DefaultConnection", 6 | "dynamicId": null 7 | } 8 | } 9 | } -------------------------------------------------------------------------------- /multiTenantApp/Services/CurrentTenantService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using multiTenantApp.Persistence.Contexts; 3 | 4 | namespace multiTenantApp.Services 5 | { 6 | public class CurrentTenantService : ICurrentTenantService 7 | { 8 | private readonly BaseDbContext _context; 9 | public string? TenantId { get; set; } 10 | public string? ConnectionString { get; set; } 11 | 12 | 13 | public CurrentTenantService(BaseDbContext context) 14 | { 15 | _context = context; 16 | 17 | } 18 | public async Task SetTenant(string tenant) 19 | { 20 | 21 | var tenantInfo = await _context.Tenants.Where(x => x.Id == tenant).FirstOrDefaultAsync(); // check if tenant exists 22 | if (tenantInfo != null) 23 | { 24 | TenantId = tenant; 25 | ConnectionString = tenantInfo.ConnectionString; // optional connection string per tenant (can be null to use default database) 26 | return true; 27 | } 28 | else 29 | { 30 | throw new Exception("Tenant invalid"); 31 | } 32 | 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /multiTenantApp/Services/ICurrentTenantService.cs: -------------------------------------------------------------------------------- 1 | namespace multiTenantApp.Services 2 | { 3 | public interface ICurrentTenantService 4 | { 5 | string? ConnectionString { get; set; } 6 | string? TenantId { get; set; } 7 | public Task SetTenant(string tenant); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /multiTenantApp/Services/ProductService/DTOs/CreateProductRequest.cs: -------------------------------------------------------------------------------- 1 | namespace multiTenantApp.Services.ProductService.DTOs 2 | { 3 | public class CreateProductRequest 4 | { 5 | public string Name { get; set; } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /multiTenantApp/Services/ProductService/IProductService.cs: -------------------------------------------------------------------------------- 1 | using multiTenantApp.Models; 2 | using multiTenantApp.Services.ProductService.DTOs; 3 | 4 | namespace multiTenantApp.Services.ProductService 5 | { 6 | public interface IProductService 7 | { 8 | IEnumerable GetAllProducts(); 9 | Product GetProductById(int id); 10 | Product CreateProduct(CreateProductRequest request); 11 | bool DeleteProduct(int id); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /multiTenantApp/Services/ProductService/ProductService.cs: -------------------------------------------------------------------------------- 1 | using multiTenantApp.Models; 2 | using multiTenantApp.Persistence.Contexts; 3 | using multiTenantApp.Services.ProductService.DTOs; 4 | 5 | namespace multiTenantApp.Services.ProductService 6 | { 7 | public class ProductService : IProductService 8 | { 9 | private readonly ApplicationDbContext _context; // database context 10 | 11 | public ProductService(ApplicationDbContext context) 12 | { 13 | _context = context; 14 | } 15 | 16 | // get a list of all products 17 | public IEnumerable GetAllProducts() 18 | { 19 | var products = _context.Products.ToList(); 20 | return products; 21 | } 22 | 23 | // get a single product 24 | public Product GetProductById(int id) 25 | { 26 | var product = _context.Products.Where(x => x.Id == id).FirstOrDefault(); 27 | return product; 28 | } 29 | 30 | // create a new product 31 | public Product CreateProduct(CreateProductRequest request) 32 | { 33 | var product = new Product(); 34 | product.Name = request.Name; 35 | 36 | _context.Add(product); 37 | _context.SaveChanges(); 38 | 39 | return product; 40 | } 41 | 42 | 43 | // delete a product 44 | public bool DeleteProduct(int id) 45 | { 46 | var product = _context.Products.Where(x => x.Id == id).FirstOrDefault(); 47 | 48 | if (product != null) 49 | { 50 | _context.Remove(product); 51 | _context.SaveChanges(); 52 | return true; 53 | } 54 | return false; 55 | } 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /multiTenantApp/Services/TenantService/DTOs/CreateTenantRequest.cs: -------------------------------------------------------------------------------- 1 | namespace multiTenantApp.Services.TenantService.DTOs 2 | { 3 | public class CreateTenantRequest 4 | { 5 | public string Id { get; set; } 6 | public string Name { get; set; } 7 | public bool Isolated { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /multiTenantApp/Services/TenantService/ITenantService.cs: -------------------------------------------------------------------------------- 1 | using multiTenantApp.Models; 2 | using multiTenantApp.Services.TenantService.DTOs; 3 | 4 | namespace multiTenantApp.Services.TenantService 5 | { 6 | public interface ITenantService 7 | { 8 | Tenant CreateTenant(CreateTenantRequest request); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /multiTenantApp/Services/TenantService/TenantService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Data.SqlClient; 2 | using Microsoft.EntityFrameworkCore; 3 | using multiTenantApp.Models; 4 | using multiTenantApp.Persistence.Contexts; 5 | using multiTenantApp.Services.TenantService.DTOs; 6 | 7 | namespace multiTenantApp.Services.TenantService 8 | { 9 | public class TenantService : ITenantService 10 | { 11 | 12 | private readonly BaseDbContext _baseDbContext; // database context 13 | private readonly IConfiguration _configuration; 14 | private readonly IServiceProvider _serviceProvider; 15 | 16 | public TenantService(BaseDbContext baseDbContext, IConfiguration configuration, IServiceProvider serviceProvider) 17 | { 18 | _baseDbContext = baseDbContext; 19 | _configuration = configuration; 20 | _serviceProvider = serviceProvider; 21 | } 22 | 23 | public Tenant CreateTenant(CreateTenantRequest request) 24 | { 25 | 26 | string connectionString = _configuration.GetConnectionString("DefaultConnection"); 27 | SqlConnectionStringBuilder builder = new(connectionString); 28 | string mainDatabaseName = builder.InitialCatalog; // retrieve the database name 29 | string tenantDbName = mainDatabaseName + "-" + request.Id; 30 | builder.InitialCatalog = tenantDbName; // set new database name 31 | string modifiedConnectionString = builder.ConnectionString; // create new connection string 32 | 33 | Tenant tenant = new() // create a new tenant entity 34 | { 35 | Id = request.Id, 36 | Name = request.Name, 37 | ConnectionString = request.Isolated ? modifiedConnectionString : null, 38 | }; 39 | 40 | 41 | try 42 | { 43 | if (request.Isolated == true) 44 | { 45 | // create a new tenant database and bring current with any pending migrations from ApplicationDbContext 46 | using IServiceScope scopeTenant = _serviceProvider.CreateScope(); 47 | ApplicationDbContext dbContext = scopeTenant.ServiceProvider.GetRequiredService(); 48 | dbContext.Database.SetConnectionString(modifiedConnectionString); 49 | if (dbContext.Database.GetPendingMigrations().Any()) 50 | { 51 | Console.ForegroundColor = ConsoleColor.Blue; 52 | Console.WriteLine($"Applying ApplicationDB Migrations for New '{request.Id}' tenant."); 53 | Console.ResetColor(); 54 | dbContext.Database.Migrate(); 55 | } 56 | } 57 | 58 | // apply changes to base db context 59 | _baseDbContext.Add(tenant); // save tenant info 60 | _baseDbContext.SaveChanges(); 61 | } 62 | catch (Exception ex) 63 | { 64 | throw new Exception(ex.Message); 65 | } 66 | 67 | return tenant; 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /multiTenantApp/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /multiTenantApp/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "DefaultConnection": "Data Source=(localdb)\\mssqllocaldb;Database=multiTenantAppDb;Trusted_Connection=True;MultipleActiveResultSets=true" 4 | }, 5 | "Logging": { 6 | "LogLevel": { 7 | "Default": "Information", 8 | "Microsoft.AspNetCore": "Warning" 9 | } 10 | }, 11 | "AllowedHosts": "*" 12 | } 13 | -------------------------------------------------------------------------------- /multiTenantApp/multiTenantApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | all 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | 19 | 20 | 21 | 22 | all 23 | runtime; build; native; contentfiles; analyzers; buildtransitive 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | --------------------------------------------------------------------------------