Currently it's expected that the factory is application scoped, while provider instances are request scoped. Factories can if they want return the same instance for provider to make it application scoped.

This works as long as config is server-wide, but not if there are config per-realm or even multiple different instances per-realm. This applies to for example User Federation SPI (multiple per-realm), Password Hashing SPI (one per-realm), etc.

Currently the User Federation SPI creates and manages instances outside of the session factory and session, which results in multiple instances created per-request, not all being closed properly, etc..

With that in mind I'd like to change the provider factories so that there can be multiple provider factory instances. It's not completely figured out, but I wanted to discuss it before I start a POC around it.

We'd have the following methods on KeycloakSession:

* getProvider(Class<T> clazz, Provider.class) - returns default provider
* getProvider(Class<T> clazz, Provider.class, String providerId) - returns a specific provider, with the default config
* getProvider(Class<T> clazz, Provider.class, String providerId, String instanceId) - returns a specific provider, with the specific config

We'd also add a method:

* invalidateProvider(Class<T> clazz, Provider.class, String providerId, String instanceId) - this would be called when the config for a specific provider instance is updated

Behind the covers the instances would be maintained. Each provider factory would internally be responsible to retrieve config and cache config for instances.

Does this sound like an idea worth pursuing? I'd like to try it out on the PasswordPolicy SPI first.