A tale of lifetimes, scopes, connection strings and query filters.

  • In this blog post…
  • Life of the factory
  • A type of method
  • Putting things in context
  • A lifetime of dependencies
  • A transient affair
  • Performance notes

You are viewing a limited version of this blog. To enable experiences like comments, opt-in to our privacy and cookie policy. Show consent dialog.

Many line of business applications are designed to work with multiple customers. It is important to secure the data so that customer data isn’t leaked and seen by other customers and potential competitors. These applications are classified as “multi-tenant” because each customer is considered a tenant of the application with their own set of data.

This article provides examples and solutions “as is.” These are not intended to be “best practices” but rather “working practices” for your consideration.

There are many approaches to implementing multi-tenancy in applications. One common approach (that is sometimes a requirement) is to keep data for each customer in a separate database. The schema is the same but the data is customer-specific. Another approach is to partition the data in an existing database by customer.

Both approaches are supported by EF Core.

For the approach that uses multiple databases, switching to the right database is as simple as providing the correct connection string. If the data is stored in a single database, a  global query filter makes sense to ensure that developers don’t accidentally write code that can access data from other customers. For a great article about how to secure a single multi-tenant database using SQL Server row-level security, check out “ Secure data in a single multi-tenant database in just 3 steps.”

Life of the factory

The recommended pattern for  using Entity Framework Core in Blazor apps is to register the  DbContextFactory, then call it to create a new instance of the DbContext each operation. By default, the factory is a singleton so only one copy exists for all users of the application. This is usually fine because although the factory is shared, the individual DbContext instances are not. For multi-tenancy, however, the connection string may change per user. Because the factory caches the configuration with the same lifetime, this means all users must share the same configuration.

This issue doesn’t occur in Blazor WebAssembly apps because the singleton is scoped to the user. Blazor Server apps, on the other hand, present a unique challenge. Although the app is a web app, it is “kept alive” by real-time communication using SignalR. A session is created per user and lasts beyond the initial request. A new factory should be provided per user to allow new settings. The lifetime for this special factory is called Scoped and creates a new instance per user session.

#blazor

Multi-tenancy with EF Core in Blazor Server Apps
8.65 GEEK