wooden-needle-52499
07/25/2023, 2:47 PMDependencyProvider (AbstractBundleDependencyProvider, AbstractDependencyProvider) and their methods such as setGlobal in one module or using configure() to set it to global like proposed here https://docs.spryker.com/docs/scos/dev/back-end-development/factory/inject-dependencies-within-factories-container-globals.html. Unfortunately, this didn't help. When adding logs I see that the code tries to access the provided dependency before it is being added. Any ideas what else I can try?plain-city-95899
07/25/2023, 3:00 PMwooden-needle-52499
07/25/2023, 3:29 PM/**
* @param Container $container
* @return Container
* @throws FrozenServiceException
*/
public function addPreviewService(Container $container): Container
{
$this->getLogger()->info("addPreviewService()");
$container->setGlobal(static::PREVIEW, function (Container $container) {
return new MyPreviewService();
});
return $container;
}
In factory of module B:
try {
$isPreview = $this->getProvidedDependency(MyDependencyProviderFromModuleA::PREVIEW)->isPreview();
$this->getLogger()->error("Got PreviewService: " . $isPreview);
return $isPreview;
} catch (\Throwable $th) {
$this->getLogger()->error("Failed to get PreviewService: " . $th->getMessage());
return false;
}
Log says:
Failed to get PreviewService: Spryker Kernel Exception
Container does not contain the called "PREVIEW"
You can fix this by adding the key "PREVIEW" to your "MyDependencyProviderFromModuleB" [then a long time afterwards (even after my twig functions ran) the log says
addPreviewService()
plain-city-95899
07/25/2023, 4:06 PMwooden-needle-52499
07/25/2023, 4:41 PMTo access this global dependency, inside your factory, callBasically I have some logic that calculates a boolean value and I want to keep my code DRY so I want it in one module only. I tried to follow the structure that the Spryker modules have.. With this approach, you can define such dependencies once instead of defining them each time for each module that uses them.$this->getProvidedDependency('Your service name')
wooden-needle-52499
07/26/2023, 10:13 AMplain-city-95899
07/26/2023, 10:28 AMplain-city-95899
07/26/2023, 10:28 AMwooden-needle-52499
07/26/2023, 10:29 AMhallowed-eye-69242
07/27/2023, 12:56 PMModuleB to get dependency from moduleA.
But you didn't execute moduleA so you don't have this dependency.
You need to provide the same dependency in moduleB too.
So, in all modules, where you use MyPreviewService you should provide this dependency first.
In the moduleB you shouldn't have MyDependencyProviderFromModuleA usage, you can use ModuleBDependencyProvider only.
Also, as @plain-city-95899 told you, you can introduce this module on Service layer and access to it using $container->getLocator()->myPreview()->service() instead of new MyPreviewService()