title: Dependency injection for Moose classes
body: <p>I have a Moose class that needs to send requests of type <code>Foo::Request</code>. I need to make this dependency accessible from the outside, so that I can easily exchange the request implementation in tests. I came up with the following attribute:</p>
  
  <pre><code>has request_builder =&gt; (
      is =&gt; 'rw',
      isa =&gt; 'CodeRef',
      default =&gt; sub {
          sub { Foo::Request-&gt;new(@_) }
      }
  );
  </code></pre>
  
  <p>And then in code:</p>
  
  <pre><code>my $self = shift;
  my $request = $self-&gt;request_builder-&gt;(path =&gt; …);
  </code></pre>
  
  <p>And in tests:</p>
  
  <pre><code>my $tested_class = …;
  my $request = Test::MockObject-&gt;new;
  $request-&gt;mock(…);
  $tested_class-&gt;request_builder(sub { $request });
  </code></pre>
  
  <p>Is there a more simple / more idiomatic solution?</p>