The question doesn't make it explicit, but since the question mentions getting an error when another module isn't installed, I take that the condition is when the module is installed. In that case, the module can simply use the following code.
public function __construct(TestService $test_service = NULL) {
$this->testService = $test_service;
}
public static function create(ContainerInterface $container) {
return new static(
$container->has('custom_form1.form1_services') ? $container->get('custom_form1.form1_services') : NULL
);
}
In this case, the class in your module should be ready not to get any class instance. Alternatively, your module could implement a simplified version of the service, which implement the same interface, and use code similar to the following one.
public function __construct(TestServiceInterface $test_service = NULL) {
$this->testService = $test_service;
}
public static function create(ContainerInterface $container) {
return new static(
$container->has('custom_form1.form1_services') ? $container->get('custom_form1.form1_services') : $container->get('mymodule.form1_services')
);
}
This assumesTestService
implements an interface that can be implemented from the simplified service. (It also assumes it's possible to implement a simplified service.)