2 Replies Latest reply on Feb 8, 2010 6:38 PM by romanb

    Scope-widening injection

    romanb

      Hi,


      from my previous experience with injectors, mainly Guice, I am aware of the scope-widening injection problem and I've been trying to find out how Weld behaves in this regard, especially since I saw the example from chapter 3 of the reference documentation where a @RequestScoped bean (Credentials) is injected into a @SessionScoped bean (Login).


      With Guice this is considered a bad thing since the bean in the narrower scope effectively continues to live on with the wider scoped bean it is injected into:



      It is usually an error for a @Singleton or @SessionScoped object to depend on an @RequestScoped one. Should you require an object in a narrower scope, inject a Provider of that object.

      (http://code.google.com/p/google-guice/wiki/Scopes)


      I experimented with the example from chapter 3 of the documentation by injecting the Credentials bean in the constructor of the Login bean (without providing a separate setter). Even in this case, Weld apparently replaced/reinjected a new Credentials instance upon subsequent invocations of login() in different requests. I assume this might be expected even though I currently have a bad feeling about this as such behavior is not reproducable outside of the container/weld, i.e. in a unit test, without resorting to reflection. When used programmatically there can obviously only be 1 Credentials instance associated with a Login instance if it is injected in the constructor and there is no setter.


      Even though Weld (re)injects the Credentials instance on subsequent requests (probably through reflection), I still think the last injected instance is subject to the scope-widening problem since it will live on together with the session-scoped Login instance.


      So my questions are:


      1) Is this current behavior of Weld correct?
      2) Is this behavior described in the spec?
      3) Anyone else care to share his thoughts on the scope-widening injection problem with regard to Weld?


      Thanks!


      Roman

        • 1. Re: Scope-widening injection
          gavin.king

          See here. The CDI implementation is required to proxy references to beans, in order to ensure that the client always sees the current instance.


          Weld does not do re-injection. It uses a proxy.



          1. Of course.

          2. Yes.

          3. IMO, it is a bug in Guice that Guice does not solve this problem.

          • 2. Re: Scope-widening injection
            romanb

            Thanks for this clarification and the pointer to the documentation. I must have missed this section before.