cdiquarkus

How to create a custom scope in Quarkus?


I tried to follow this instruction https://rpestano.wordpress.com/2013/06/30/cdi-custom-scope/ , but it's not working, because the methods of my custom Context are not fired.


Solution

  • You can declare custom scopes in Quarkus. However, Quarkus does not use a full CDI implementation, instead it has a lighter implementation that does not support everything you know from CDI the way you are used to. Reasons are multiple but mostly it is done in order to make it build time friendly.

    CDI extensions are one of the things that are inherently runtime based and as such are a bad fit for Quarkus stuff. Instead, you will have to use a Quarkus extension to declare your scope/context. Let me give you some materials for that...

    Here is a link to Quarkus CDI guide in general, it lists its limitations and how it compensates for it.

    This bit in particular shows how to register a custom scope within extension. The method is as simple as:

    @BuildStep
    ContextRegistrarBuildItem customContext() {
        return new ContextRegistrarBuildItem(new ContextRegistrar() {
             public void register(RegistrationContext registrationContext) {
                registrationContext.configure(CustomScoped.class).normal().contextClass(MyCustomContext.class).done();
             }
        });
    }
    

    And here is a link to how Narayana Quarkus extension uses this exact same API to register @Transactional. The underlying context class is very similar to what you would use in CDI (or in Weld), take a look at this class that Narayana uses for inspiration.