Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migration of unmigrated content due to installation of a new plugin

Wiki Markup
{scrollbar}

Overriding Tapestry IoC Services

...

In most cases, services are injected by matching just the type; there is no @InjectService annotation, just a method or constructor parameter whose type matches the service's interface.

In this case, it is very easy to supply your own alternate implementation of a service, by contributing a Service Override in your module class (usually AppModule.java), like this:

Code Block
lang
langjava
titleAppModule.java (partial)java

  @Contribute(ServiceOverride.class)
  public static void setupApplicationServiceOverrides(MappedConfiguration<Class,Object> configuration)
  {
    configuration.addInstance(SomeServiceType.class, SomeServiceTypeOverrideImpl.class);
  }

...

In this example, we are using addInstance() which will instantiate the indicated class and handle dependency resolution

Wiki Markup
{footnote}Be careful with this, because in some cases, resolving dependencies of the override class can require checking against the ServiceOverrides service, and you'll get a runtime exception about ServiceOverrides requiring itself!{footnote}

. (Be careful with this, because in some cases, resolving dependencies of the override class can require checking against the ServiceOverrides service, and you'll get a runtime exception about ServiceOverrides requiring itself!).

Sometimes you'll want to define the override as a service of its own: this . This is useful if you want to inject a Logger specific to the service, or if the overriding implementation needs a service configuration:

Code Block
langjava
titleAppModule.java (partial)
langjava

  public static void bind(ServiceBinder binder)
  {
    binder.bind(SomeServiceType.class, SomeServiceTypeOverrideImpl.class).withId("SomeServiceTypeOverride");
  }

  @Contribute(ServiceOverride.class)
  public static void setupApplicationServiceOverrides(MappedConfiguration<Class,Object> configuration, @Local SomeServiceType override)
  {
    configuration.add(SomeServiceType.class, override);
  }

...

Alternately, this approach is useful to override a service that is matched using marker annotations.

Code Block
lang
langjava
titleAppModule.java (partial)java

  public SomeServiceType decorateSomeServiceType(final SomeServiceType delegate)
  {
    return new SomeServiceType() { . . . };
  }

...

Note that the object passed in as delegate may be the core service implementation, or it may be some other interceptor from some other decorator for the same service.

...

 

 

{display-footnotes}
Wiki Markup
Wiki Markup
{scrollbar}