Preslav Rachev
Preslav Rachev

Reputation: 4003

Binding multiple implementations, depending on the host class

I have two interfaces: UserService and ProjectService. Each of them has a specific implementation class, named UserServiceImpl and ProjectServiceImpl, respectively. There is also a WorkflowManagementService class, which implements the two aforementioned interfaces, and works as a proxy for their concrete implementations. It also does more stuff on top.

The WorkflowManagementService gets injected with concrete UserService and ProjectService instances. For the rest of the application though, whenever someone needs a UserSerivce or a ProjectService instance, a WorkflowManagementService should be provided.

How can I make so that the injector provides UserServiceImpl and ProjectServiceImpl, if they are to be injected in WorkflowManagementService, and WorkflowManagementService for any other reference?

Upvotes: 0

Views: 151

Answers (1)

condit
condit

Reputation: 10962

I don't know of a way to do this based on class context but you could do this with a binding annotation:

public class Example {

  static interface UserService {}
  static interface ProjectService {}

  static class UserServiceImpl implements UserService {}
  static class ProjectServiceImpl implements ProjectService {}

  static class WorkflowManagementService implements UserService, ProjectService {
    @Inject
    @Named("concrete")
    UserService userService;

    @Inject
    @Named("concrete")
    ProjectService projectService;
  }

  static class Module extends AbstractModule {
    @Override
    protected void configure() {
      bind(UserService.class).to(WorkflowManagementService.class);
      bind(ProjectService.class).to(WorkflowManagementService.class);
      bind(UserService.class).annotatedWith(Names.named("concrete")).to(UserServiceImpl.class);
      bind(ProjectService.class).annotatedWith(Names.named("concrete")).to(ProjectServiceImpl.class);
    }
  }
}

You might want to use an actual annotation instead of @Named after you finish prototyping your code.

Upvotes: 1

Related Questions