Repository: quarkusio/quarkus
Issue: Hibernate Multitenant project with a @RequestScoped TenantResolver throws javax.enterprise.context.ContextNotActiveException

### Describe the bug

I'm using the `SCHEMA` hibernate multitenant option, implementing a `TenantResolver` that is `@RequestScoped` so that I can use an `@Inject`ed `JsonWebToken`

At startup, the app logs a warning when trying to call the `getDefaultTenantId` method to get the connection metadata ( see below ). This happens in 2.1.*, and didn't happen in 1.1.*, so it seems a regression.

More severe is that if I use the hibernate migrations(*), the app won't start as it can't get the default tenant. The error stack is similar but it's triggered from the migration classes. See the attached multitenant-2.1.2-migrate.zip file

```
2021-08-17 23:16:05,767 ERROR [io.qua.run.Application] (Quarkus Main Thread) Failed to start application (with profile dev): javax.enterprise.context.ContextNotActiveException
	at io.quarkus.arc.impl.ClientProxies.getDelegate(ClientProxies.java:40)
	at io.portx.quarkus.multitenant.CableTenantResolver_ClientProxy.arc$delegate(CableTenantResolver_ClientProxy.zig:42)
	at io.portx.quarkus.multitenant.CableTenantResolver_ClientProxy.getDefaultTenantId(CableTenantResolver_ClientProxy.zig:128)
	at io.quarkus.hibernate.orm.runtime.tenant.HibernateMultiTenantConnectionProvider.getAnyConnectionProvider(HibernateMultiTenantConnectionProvider.java:37)
	at org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider.getAnyConnection(AbstractMultiTenantConnectionProvider.java:26)
	at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$MultiTenantConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:208)
	at org.hibernate.resource.transaction.backend.jta.internal.DdlTransactionIsolatorJtaImpl.<init>(DdlTransactionIsolatorJtaImpl.java:59)
	at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl.buildDdlTransactionIsolator(JtaTransactionCoordinatorBuilderImpl.java:46)
	at org.hibernate.tool.schema.internal.HibernateSchemaManagementTool.getDdlTransactionIsolator(HibernateSchemaManagementTool.java:189)
	at org.hibernate.tool.schema.internal.HibernateSchemaManagementTool.buildGenerationTargets(HibernateSchemaManagementTool.java:147)
	at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:110)
	at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:153)
	at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:81)
	at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:327)
	at io.quarkus.hibernate.orm.runtime.boot.FastBootEntityManagerFactoryBuilder.build(FastBootEntityManagerFactoryBuilder.java:71)
	at io.quarkus.hibernate.orm.runtime.FastBootHibernatePersistenceProvider.createEntityManagerFactory(FastBootHibernatePersistenceProvider.java:67)
	at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:80)
	at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
	at io.quarkus.hibernate.orm.runtime.JPAConfig$LazyPersistenceUnit.get(JPAConfig.java:149)
	at io.quarkus.hibernate.orm.runtime.JPAConfig$1.run(JPAConfig.java:58)
	at java.base/java.lang.Thread.run(Thread.java:829)
```

(*) I know that https://quarkus.io/guides/hibernate-orm#configuring-the-application doesn't recommend using the hibernate generation with a multitenant config, but it's useful for a dev or test setup where I run just one schema.


To avoid this warning/error, as a workaround I have to use an `@ApplicationScoped` TenantResolver and then get the JsonWebToken "manually" using: 
```java
    if ( Arc.container().requestContext().isActive() ) {
      jwt = CDI.current().select(JsonWebToken.class).get();
    } else {
      throw new RuntimeException("Could not extract tenant information from JWT because the RequestContext is not active");
    }
```

Here's the full stack trace:


```
2021-08-17 22:04:56,066 WARN  [org.hib.eng.jdb.env.int.JdbcEnvironmentInitiator] (JPA Startup Thread: <default>) HHH000342: Could not obtain connection to query metadata: javax.enterprise.context.ContextNotActiveException
	at io.quarkus.arc.impl.ClientProxies.getDelegate(ClientProxies.java:40)
	at io.portx.quarkus.multitenant.CableTenantResolver_ClientProxy.arc$delegate(CableTenantResolver_ClientProxy.zig:42)
	at io.portx.quarkus.multitenant.CableTenantResolver_ClientProxy.getDefaultTenantId(CableTenantResolver_ClientProxy.zig:128)
	at io.quarkus.hibernate.orm.runtime.tenant.HibernateMultiTenantConnectionProvider.getAnyConnectionProvider(HibernateMultiTenantConnectionProvider.java:37)
	at org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider.getAnyConnection(AbstractMultiTenantConnectionProvider.java:26)
	at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$MultiTenantConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:208)
	at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68)
	at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
	at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101)
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
	at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
	at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:107)
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:246)
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
	at org.hibernate.boot.internal.SessionFactoryOptionsBuilder.<init>(SessionFactoryOptionsBuilder.java:263)
	at io.quarkus.hibernate.orm.runtime.recording.PrevalidatedQuarkusMetadata.buildSessionFactoryOptionsBuilder(PrevalidatedQuarkusMetadata.java:69)
	at io.quarkus.hibernate.orm.runtime.boot.FastBootEntityManagerFactoryBuilder.build(FastBootEntityManagerFactoryBuilder.java:69)
	at io.quarkus.hibernate.orm.runtime.FastBootHibernatePersistenceProvider.createEntityManagerFactory(FastBootHibernatePersistenceProvider.java:67)
	at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:80)
	at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
	at io.quarkus.hibernate.orm.runtime.JPAConfig$LazyPersistenceUnit.get(JPAConfig.java:149)
	at io.quarkus.hibernate.orm.runtime.JPAConfig$1.run(JPAConfig.java:58)
	at java.base/java.lang.Thread.run(Thread.java:829)
```


### Expected behavior

No warnings, TenantResolver created and `getDefaultTenantId` called

### Actual behavior

See stack trace above

### How to Reproduce?

I'm adding a mvn project to reproduce the error. Run `./mvnw compile quarkus:dev`
[multitenant-2.1.2.zip](https://github.com/quarkusio/quarkus/files/7003865/multitenant-2.1.2.zip)

Compare with the 1.1.7 version which runs ok ( this needs a pg db running )
[1.1.7.zip](https://github.com/quarkusio/quarkus/files/7003993/1.1.7.zip)


### Output of `uname -a` or `ver`

Darwin MBP-15-Ramiro.local 20.4.0 Darwin Kernel Version 20.4.0: Thu Apr 22 21:46:47 PDT 2021; root:xnu-7195.101.2~1/RELEASE_X86_64 x86_64

### Output of `java -version`

openjdk version "11.0.11" 2021-04-20 OpenJDK Runtime Environment AdoptOpenJDK-11.0.11+9 (build 11.0.11+9) OpenJDK 64-Bit Server VM AdoptOpenJDK-11.0.11+9 (build 11.0.11+9, mixed mode)

### GraalVM version (if different from Java)

not used

### Quarkus version or git rev

2.1.2.Final

### Build tool (ie. output of `mvnw --version` or `gradlew --version`)

Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f) Maven home: /Users/ramiro/.m2/wrapper/dists/apache-maven-3.6.3-bin/1iopthnavndlasol9gbrbg6bf2/apache-maven-3.6.3 Java version: 11.0.11, vendor: AdoptOpenJDK, runtime: /Users/ramiro/.sdkman/candidates/java/11.0.11.hs-adpt Default locale: en_AR, platform encoding: UTF-8 OS name: "mac os x", version: "11.3", arch: "x86_64", family: "mac"

### Additional information

_No response_

Changed files:
extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/tenant/HibernateMultiTenantConnectionProvider.java

diff --git a/extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/tenant/HibernateMultiTenantConnectionProvider.java b/extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/tenant/HibernateMultiTenantConnectionProvider.java
index ddf8000db0f..141965ec47b 100644
--- a/extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/tenant/HibernateMultiTenantConnectionProvider.java
+++ b/extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/tenant/HibernateMultiTenantConnectionProvider.java
@@ -1,9 +1,12 @@
 package io.quarkus.hibernate.orm.runtime.tenant;
 
+import java.lang.annotation.Annotation;
 import java.util.Locale;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 
+import javax.enterprise.context.RequestScoped;
+import javax.enterprise.context.SessionScoped;
 import javax.enterprise.inject.Default;
 
 import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider;
@@ -12,6 +15,7 @@
 
 import io.quarkus.arc.Arc;
 import io.quarkus.arc.InstanceHandle;
+import io.quarkus.arc.ManagedContext;
 import io.quarkus.hibernate.orm.PersistenceUnit.PersistenceUnitLiteral;
 import io.quarkus.hibernate.orm.runtime.PersistenceUnitUtil;
 
@@ -19,7 +23,6 @@
  * Maps from the Quarkus {@link TenantConnectionResolver} to the {@link HibernateMultiTenantConnectionProvider} model.
  *
  * @author Michael Schnell
- *
  */
 public final class HibernateMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider {
 
@@ -34,7 +37,23 @@ public HibernateMultiTenantConnectionProvider(String persistenceUnitName) {
 
     @Override
     protected ConnectionProvider getAnyConnectionProvider() {
-        String tenantId = tenantResolver(persistenceUnitName).getDefaultTenantId();
+        InstanceHandle<TenantResolver> tenantResolver = tenantResolver(persistenceUnitName);
+        String tenantId;
+        // Activate RequestScope if the TenantResolver is @RequestScoped or @SessionScoped
+        ManagedContext requestContext = Arc.container().requestContext();
+        Class<? extends Annotation> tenantScope = tenantResolver.getBean().getScope();
+        boolean requiresRequestScope = (tenantScope == RequestScoped.class || tenantScope == SessionScoped.class);
+        boolean forceRequestActivation = (!requestContext.isActive() && requiresRequestScope);
+        try {
+            if (forceRequestActivation) {
+                requestContext.activate();
+            }
+            tenantId = tenantResolver.get().getDefaultTenantId();
+        } finally {
+            if (forceRequestActivation) {
+                requestContext.deactivate();
+            }
+        }
         if (tenantId == null) {
             throw new IllegalStateException("Method 'TenantResolver.getDefaultTenantId()' returned a null value. "
                     + "This violates the contract of the interface!");
@@ -88,7 +107,7 @@ private static ConnectionProvider resolveConnectionProvider(String persistenceUn
      *
      * @return Current tenant resolver.
      */
-    private static TenantResolver tenantResolver(String persistenceUnitName) {
+    private static InstanceHandle<TenantResolver> tenantResolver(String persistenceUnitName) {
         InstanceHandle<TenantResolver> resolverInstance;
         if (PersistenceUnitUtil.isDefaultPersistenceUnit(persistenceUnitName)) {
             resolverInstance = Arc.container().instance(TenantResolver.class, Default.Literal.INSTANCE);
@@ -102,7 +121,7 @@ private static TenantResolver tenantResolver(String persistenceUnitName) {
                             + "You need to create an implementation for this interface to allow resolving the current tenant identifier.",
                     TenantResolver.class.getSimpleName(), persistenceUnitName));
         }
-        return resolverInstance.get();
+        return resolverInstance;
     }
 
 }