When requesting dependencies, the implementations may differ for various contexts. DiVine lets you specify factories, which have the purpose of creating instances based on the given parameters.
voidrequestDependency() {AmazingService service =Container.get(AmazingService,"EXAMPLE_PARAMETER");}
Note that parameter arguments are checked at runtime, so factory types are guaranteed inside the factory class.
The following code showcases a simple way of requesting different implementations for a service.
@Service(// use the `CarFactory` class to create new instances for the `Car` type factory =CarFactory.class,// use `TRANSIENT` scope, to create a new car instance, each time a car // is requested scope =ServiceScope.TRANSIENT)interfaceCar {voiddrive();}enumCarType { MERCEDES, BMW, FERRARI}classCarFactoryimplementsFactory<Car,CarType// you may specify any arbitrary factoryparameter type> { @Overridepublic @NotNullCarcreate( @NotNullService descriptor, @NotNullClass<?extendsCar> type, @NotNullClass<?> context, @NullableCarType carType ) {returnswitch (carType) {case MERCEDES ->newMercedesCar();case BMW ->newBMWCar();case FERRARI ->newFerrariCar(); }; }}@ServiceclassCarDealership() {publicCarorderCar(CarType type) {returnContainer.get(Car.class, type); }}voidorderCars() {CarDealership dealership =Container.get(CarDealership.class);assertdealership.orderCar(CarType.MERCEDES) instanceof MercedesCar;assertdealership.orderCar(CarType.BMW) instanceof BMWCar;assertdealership.orderCar(CarType.FERRARY) instanceof FerraryCar;}