@@ -1508,6 +1508,81 @@ implementing ``MessageFormatterInterface`` that will forward calls of
1508
1508
``MessageFormatterInterface::format() `` to your underlying service's method
1509
1509
``MessageUtils::format() ``, with all its arguments.
1510
1510
1511
+ Injecting Anonymous Services / Inlined Services
1512
+ -----------------------------------------------
1513
+
1514
+ In some cases it may happen where you'd want to inject a service that requires
1515
+ a specified parameter that can't be autowired.
1516
+
1517
+ Let's take this here as an example::
1518
+
1519
+ class SomeSourceAwareLogger
1520
+ {
1521
+ public function __construct(
1522
+ private readonly LoggerInterface $logger,
1523
+ private readonly string $someSource,
1524
+ ) {
1525
+ }
1526
+
1527
+ public function error(string $someMessage): void
1528
+ {
1529
+ $this->logger->error(
1530
+ sprintf('[%s]: %s', $this->someSource, $someMessage),
1531
+ );
1532
+ }
1533
+ }
1534
+
1535
+ Let's assume we'd want to provide a source depending on wherever we are to decorate
1536
+ our log messages with that information. We could also pass the source as a argument
1537
+ to a log method but that would cause unnecessary duplication / usages whenever we'd
1538
+ want to log something.
1539
+
1540
+ For these cases there's now the :class: `Symfony\\ Component\\ DependencyInjection\\ Attribute\\ AutowireInline `
1541
+ attribute that can be used to autowire a service / class and inject a new instance
1542
+ of the requested service.
1543
+ Let's see it in action::
1544
+
1545
+ namespace App\Service;
1546
+
1547
+ use App\Service\SomeSourceAwareLogger;
1548
+ use Symfony\Component\DependencyInjection\Attribute\AutowireInline;
1549
+
1550
+ class SomeService
1551
+ {
1552
+ public function __construct(
1553
+ #[AutowireInline(SomeSourceAwareLogger::class, [
1554
+ '$someSource' => 'SomeSelfDefinedSource',
1555
+ ])]
1556
+ private SomeSourceAwareLogger $logger1,
1557
+ #[AutowireInline(SomeSourceAwareLogger::class, [
1558
+ '$someSource' => 'SomeOtherSource',
1559
+ ])]
1560
+ private SomeSourceAwareLogger $logger2,
1561
+ ) {
1562
+ }
1563
+
1564
+ public function doSomething(): void
1565
+ {
1566
+ try {
1567
+ // ...
1568
+ } catch (\Exception $exception) {
1569
+ $this->logger1->error($exception->getMessage());
1570
+ }
1571
+ }
1572
+
1573
+ public function doSomethingDifferent(): void
1574
+ {
1575
+ try {
1576
+ // ...
1577
+ } catch (\Exception $exception) {
1578
+ $this->logger2->error($exception->getMessage());
1579
+ }
1580
+ }
1581
+ }
1582
+
1583
+ Instead of using the ``#[AutowireInline] `` attribute, you can still achieve
1584
+ the same by using the :ref: `configuration files <anonymous-services >`.
1585
+
1511
1586
Learn more
1512
1587
----------
1513
1588
0 commit comments