A needle ejection and retraction mechanism (10) comprises a needle (12), a needle hub (14) connected to the needle (12) and adapted to be displaced in a distal direction and in a proximal direction, a first spring mechanism (16) compressed to exert a force in the distal direction on the needle hub (14) and adapted to cause the needle (12) to eject in the distal direction, a second spring mechanism (18) compressed to exert a force in the proximal direction on the needle hub (14) and adapted to cause the needle (12) to retract in the proximal direction after it has been ejected in the distal direction, and an actuator (20) which is adapted to activate the exertion of the force in the distal direction on the needle hub (14) and the exertion of the force in the proximal direction on the needle hub (14). An injector device comprises a needle ejection and retraction mechanism (10), a control unit which is adapted to control the actuator (20), and a sensor unit which is connected to a control unit and which is adapted to determine, after the needle (12) has at least been partially ejected from the injector device, a value which indicates a distance between the sensor unit and the skin of a human or animal body, wherein the control unit is adapted, upon determination that the value exceeds a predetermined threshold value, to cause the actuator to activate the exertion of the force in the proximal direction on the needle hub (14) so that a distal tip (13) of the needle (12) does not protrude from the injector device.