How to do a request scoped dependency injection with Guice? I am getting [No scope is bound to RequestScoped] run time error

Viewed 16

I am trying to do a simple dependency injection with Guice for a request scoped object that should be different for every request but the same across the request itself.

Provider:

import com.google.inject.servlet.RequestScoped;

@RequestScoped
public class MyServiceProvider implements Provider<MyService> {

  @Override
  public ExperimentService get() {
    return new MyService();
  }

}

Module:

import com.google.inject.servlet.RequestScoped;

public class CommonModule extends AbstractModule {

  @Override
  protected void configure() {
     bind(MyService.class).toProvider(MyServiceProvider.class).in(RequestScoped.class);
  }

}

Usage:

public class SomeClass {

  @Inject
  private MyService myservice;

}

However I am getting a runtime error when the servlet start with the following error:

Caused by: com.google.inject.CreationException: Unable to create injector, see the following errors:

1) [Guice/ScopeNotFound]: No scope is bound to RequestScoped.

Used at:
1  : MyModule.configure(MyModule.java:50)
      \_ installed by: SomeOtherModule -> MyModule
2  : MyServiceProvider.class(MyServiceProvider.java:11)
     at MyModule.configure(MyModule.java:50)
      \_ installed by: SomeOtherModule -> MyModule

Learn more:
  https://github.com/google/guice/wiki/SCOPE_NOT_FOUND

1 error

What exactly am I doing wrong and what does this error even mean?

0 Answers
Related