geoip2 icon indicating copy to clipboard operation
geoip2 copied to clipboard

How to use Service injection in Symfony 6 properly

Open TheAFOGroup opened this issue 2 years ago • 1 comments

Hi, thanks for the library!

I`m having quite some trouble understanding what the heck is going on. Basically, I want a service that I can use in Controllers and EventListeners.

After checking the issues here and comments, you mentioned to declare:

GeoIp2\Database\Reader:
        alias: 'geoip2.reader'
        public: true

However, this is not needed apparently. The moment you pass use GeoIp2\Database\Reader into the constructor, the following gets injected:

[ContainerLx2Tlzg\Reader_5400306 - GeoIp2\Database\Reader@proxy](http://.../_profiler/open?file=var\cache\dev\ContainerLx2Tlzg\Reader_5400306.php&line=7#line7) {#643 ▼
  -valueHolder16a63: null
  -initializer876c2: [Closure(&$wrappedInstance, LazyLoadingInterface $proxy)](http://.../_profiler/open?file=var\cache\dev\ContainerLx2Tlzg\**getGeoip2_Database_CityReaderService**.php&line=22#line22) {#647 ▼
    class: "[ContainerLx2Tlzg\getGeoip2_Database_CityReaderService](http://.../_profiler/open?file=var\cache\dev\ContainerLx2Tlzg\getGeoip2_Database_CityReaderService.php&line=11#line11)"
    use: {▼
      $container: ContainerLx2Tlzg\App_KernelDevDebugContainer {#55 …}
    }
  }

As above the City reader gets injected automatically, and I have no way of getting the ASN reader for example. I have also commented out default_database but without any effect.

So back to my question, how to use your library properly and as intended?

The requirement is quite simple:

  • Be able to use any reader in Controllers, EventListeners without injecting the ReaderFactory, just use the already there service.

Many thanks!

TheAFOGroup avatar Jun 26 '22 08:06 TheAFOGroup

If you have several reader services, then Symfony dependency injector will not be able to automatically determine which one to inject, because for Symfony injector, these services are the same and only you know which one to use where. You will have to explicitly describe dependency injection in configs or use a ReaderFactory or create a proxy classes for each databases.

peter-gribanov avatar Jun 27 '22 09:06 peter-gribanov