MultiTenantDbFactory

I’m trying to create an implementation of IDbConnectionFactory. The documentation provides an implementation of called MultiTenantDbFactory but this doesn’t compile. It depends on the variable RequestContext and the class doesn’t have access to this variable. I thought it might be static (which would be bad) but it doesn’t seem as though there is a static variable called RequestContext. How can this class access the request? Shouldn’t the request be injected via the constructor?

Wait…

It turns out that it is static. And from reading XML doc, it seems as though it somehow shares the data by the current thread? That seems pretty messy. How do we guarantee that two separate threads aren’t trying to access the data here? How do we ensure that we are getting the correct request data? Where are the headers?

Which code doesn’t compile? If it helps here’s the complete source code in MultiTennantAppHostTests.cs (compilable on all supported platforms).

RequestContext enables Thread Safe Singleton access to Request Items akin to ASP .NET Core’s built-in IHttpContextAccessor, e.g. uses AsyncLocal storage in ASP .NET Core or uses HttpContext.Current in classic ASP .NET Framework so MultiTenantDbFactory is a ThreadSafe singleton.

You shouldn’t be trying to implement IDbConnectionFactory, you’ll only use if you’re using OrmLite to dynamically open named connections to your Tennants RDBMS.

1 Like

Thanks. How is it thread-safe? Does each request have a thread, and the static variable keeps a dictionary of items by a thread? I.e. can we guarantee that if two requests try to access this at the same time they will not affect each other?

The same way ASP .NET Core’s IHttpContextAccessor and ASP .NET’s HttpContext.Current is thread safe, they’re singletons providing access to the Request Context managed by the framework for the currently executing HTTP Request Worker thread.

The same way ASP .NET Core’s IHttpContextAccessor and ASP .NET’s HttpContext.Current is thread safe, they’re singletons providing access to the Request Context managed by the framework for the currently executing HTTP Request Worker thread.

Ok, so, is it guaranteed that two separate requests cannot affect each other’s items?

Right, 2 HTTP Requests will only have access to their own Request Context, as such it’s only accessible from the HTTP Request Worker Thread, i.e. you can’t access the HTTP Request Context in any spawned Background threads.

1 Like