31

I'm currently building a learner React/Redux Application and I can not wrap my head around how to do dependency injection for services.

To be more specific: I have a BluetoothService (which abstracts a 3rd Party Library) to scan for and connect to other devices via bluetooth. This service gets utilized by the action creators, something like this:

deviceActionCreators.js:

const bluetoothService = require('./blueToothService')
function addDevice(device) {
   return { type: 'ADD_DEVICE', device }
}

function startDeviceScan() {
   return function (dispatch) {
      // The Service invokes the given callback for each found device
      bluetoothService.startDeviceSearch((device) => {
          dispatch(addDevice(device));
      });
   }
}
module.exports = { addDevice, startDeviceScan };

(I am using the thunk-middleware)

My Problem however is: how to inject the service itself into the action-creator?

I don't want that hard-coded require (or importin ES6) as I don't think this is a good pattern - besides making testing so much harder. I also want to be able to use a mock-service while testing the app on my work station (which doesn't have bluetooth) - so depending on the environment i want another service with the same interface injected inside my action-creator. This is simply not possible with using a static import.

I already tried making the bluetoothService a parameter for the Method itself (startDeviceScan(bluetoothService){}) - effectively making the method itself pure - but that just moves the problem to the containers using the action. Every container would have to know about the service then and get an implementation of it injected (for example via props). Plus when I want to use the action from within another action I end up with the same problem again.

The Goal: I want to decide on bootstrapping time which implemenation to use in my app. Is there a good way or best practice for doing this?

4 Answers 4

25

React-thunk supports passing an arbitrary object to a thunk using withExtraArgument. You can use this to dependency-inject a service object, e.g.:

const bluetoothService = require('./blueToothService');

const services = {
    bluetoothService: bluetoothService
};

let store = createStore(reducers, {},
    applyMiddleware(thunk.withExtraArgument(services))
);

Then the services are available to your thunk as a third argument:

function startDeviceScan() {
    return function (dispatch, getstate, services) {
        // ...
        services.bluetoothService.startDeviceSearch((device) => {
            dispatch(addDevice(device));
        });
    }
}

This is not as formal as using a dependency-injection decorator in Angular2 or creating a separate Redux middleware layer to pass services to thunks---it's just an "anything object" which is kind of ugly---but on the other hand it's fairly simple to implement.

4
  • 1
    This doesn't seem like DI, it seems more like Service Location, an anti-pattern.
    – Ash
    Commented Feb 13, 2020 at 23:46
  • @Ash it would be Service Location if startDeviceScan were responsible for creating the bluetoothService. As it is, it has no idea how that service was created---it received it during initialization.
    – mikebridge
    Commented Feb 14, 2020 at 18:27
  • 1
    Not quite. Using the Service Locator (SL) pattern doesn’t imply creation of the particular service, I think what you’re thinking of there is possibly the Factory pattern. It’s SL if you reference the locator, either via a static reference to its class or (in your case) an instance of it, in order to receive an instance of the actual required type. In your case, even though the (services) locator is passed in (and therefore that bit is DI), the fact that the method uses it to receive the actual intended type (bluetoothService) means it’s using SL.
    – Ash
    Commented Feb 15, 2020 at 0:10
  • From Martin Fowler: “The basic idea behind a service locator is to have an object that knows how to get hold of all the services that an application might need.” In your case that object is services. Wherher or not it’s injected into a method is irrelevant - as long as the method uses it, it’ll be making use of SL.
    – Ash
    Commented Feb 15, 2020 at 0:34
13

You can use a redux middleware that will respond to an async action. In this way you can inject whatever service or mock you need in a single place, and the app will be free of any api implementation details:

// bluetoothAPI Middleware
import bluetoothService from 'bluetoothService';

export const DEVICE_SCAN = Symbol('DEVICE_SCAN'); // the symbol marks an action as belonging to this api

// actions creation helper for the middleware
const createAction = (type, payload) => ({ 
    type,
    payload
});

// This is the export that will be used in the applyMiddleware method
export default store => next => action => {
    const blueToothAPI = action[DEVICE_SCAN];

    if(blueToothAPI === undefined) {
        return next(action);
    }

    const [ scanDeviceRequest, scanDeviceSuccess, scanDeviceFailure ] = blueToothAPI.actionTypes;

    next(createAction(scanDeviceRequest)); // optional - use for waiting indication, such as spinner

    return new Promise((resolve, reject) => // instead of promise you can do next(createAction(scanDeviceSuccess, device) in the success callback of the original method
        bluetoothService.startDeviceSearch((device) => resolve(device), (error) = reject(error)) // I assume that you have a fail callback as well
        .then((device) => next(createAction(scanDeviceSuccess, device))) // on success action dispatch
        .catch((error) => next(createAction(scanDeviceFailure, error ))); // on error action dispatch
};

// Async Action Creator
export const startDeviceScan = (actionTypes) => ({
    [DEVICE_SCAN]: {
        actionTypes
    }
});

// ACTION_TYPES
export const SCAN_DEVICE_REQUEST = 'SCAN_DEVICE_REQUEST'; 
export const SCAN_DEVICE_SUCCESS = 'SCAN_DEVICE_SUCCESS'; 
export const SCAN_DEVICE_FAILURE = 'SCAN_DEVICE_FAILURE';

// Action Creators - the actions will be created by the middleware, so no need for regular action creators

// Applying the bluetoothAPI middleware to the store
import { createStore, combineReducers, applyMiddleware } from 'redux'
import bluetoothAPI from './bluetoothAPI';

const store = createStore(
  reducers,
  applyMiddleware(bluetoothAPI);
);

// Usage
import { SCAN_DEVICE_REQUEST, SCAN_DEVICE_SUCCESS, SCAN_DEVICE_FAILURE } from 'ACTION_TYPES';

dispatch(startDeviceScan([SCAN_DEVICE_REQUEST, SCAN_DEVICE_SUCCESS, SCAN_DEVICE_FAILURE]));

You dispatch the startDeviceScan async action, with the action types that will be used in the creation of the relevant actions. The middleware identifies the action by the symbol DEVICE_SCAN. If the action doesn't contain the symbol, it dispatches it back to the store (next middleware / reducers).

If the symbol DEVICE_SCAN exists, the middleware extracts the action types, creates and dispatches a start action (for a loading spinner for example), makes the async request, and then creates and dispatches a success or failure action.

Also look at the real world redux middle example.

4
  • 2
    Thanks a lot for that detailed answer. I read about middleware before but didn't fully grasp it until now. Would you say this is the standard or best practice for using services in a react-redux app? Commented Apr 2, 2016 at 21:12
  • 1
    Welcome - I struggled with it as well :)
    – Ori Drori
    Commented Apr 2, 2016 at 21:13
  • Thank you! Using this I was able to get angular dependency injection working seamlessly with redux and redux-thunk, which will make our transition from Angular to React much smoother: gist.github.com/jasononeil/e835aeb2ce7b9f099616ef2098caac1d Commented Dec 5, 2016 at 2:25
  • Glad it helped :) I liked the angular middleware, especially the idea with the injector. I suggest that you won't use only typeof action === 'function' as the middleware check. If you'll use other methods, they'll be annotated as well. Add a simple type to the function - action.type = 'whatever', and check for the type.
    – Ori Drori
    Commented Dec 5, 2016 at 17:29
2

Can you wrap your action creators into their own service?

export function actionCreatorsService(bluetoothService) {
   function addDevice(device) {
      return { type: 'ADD_DEVICE', device }
   }

   function startDeviceScan() {
      return function (dispatch) {
         // The Service invokes the given callback for each found device
         bluetoothService.startDeviceSearch((device) => {
            dispatch(addDevice(device));
         });
      }
   }

   return {
      addDevice,
      startDeviceScan
   };
}

Now, any clients of this service will need to provide an instance of the bluetoothService. In your actual src code:

const bluetoothService = require('./actual/bluetooth/service');
const actionCreators = require('./actionCreators')(bluetoothService);

And in your tests:

const mockBluetoothService = require('./mock/bluetooth/service');
const actionCreators = require('./actionCreators')(mockBluetoothService);

If you don't want to specify the bluetooth service every time you need to import the action creators, within the action creators module you can have a normal export (that uses the actual bluetooth service) and a mock export (that uses a mock service). Then the calling code might look like this:

const actionCreators = require('./actionCreators').actionCreators;

And your test code might look like this:

const actionCreators = require('./actionCreators').mockActionCreators;
2
  • 1
    Thanks for the quick answer. Wrapping the whole creator as a service with DI is a good solution in itself - but it leaves me with the same problem as when i tried it as DI in the function: The Containers (or Clients) using the action-creators have to decide which service to use. But I want to make that decision already before while bootstrapping the whole app, so maybe already in the main.js-File. Would you then pass the service to use around in properties? Commented Apr 2, 2016 at 16:09
  • I haven't used an DI libraries for JS (besides Angular), but it might be worth investigating some libraries specifically built for this. Other solutions I've seen are to use environment variables to determine what to export (ie your bluetoothService module might export the mock service if some env variable is set). Commented Apr 2, 2016 at 16:44
2

I created a dependency-injecting middleware called redux-bubble-di for exactly that purpose. It can be used to inject an arbitrary number of dependencies into action creators.

You can install it by npm install --save redux-bubble-di or download it.

Your example using redux-bubble-di would look like this:

//import { DiContainer } from "bubble-di";
const { DiContainer } = require("bubble-di");
//import { createStore, applyMiddleware } from "redux";
const { createStore, applyMiddleware } = require("redux");
//import reduxBubbleDi from "redux-bubble-di";
const reduxBubbleDi = require("redux-bubble-di").default;

const bluetoothService = require('./blueToothService');

DiContainer.setContainer(new DiContainer());
DiContainer.getContainer().registerInstance("bluetoothService", bluetoothService);

const store = createStore(
    state => state,
    undefined,
    applyMiddleware(reduxBubbleDi(DiContainer.getContainer())),
);

const startDeviceScan = {
    bubble: (dispatch, bluetoothService) => {
        bluetoothService.startDeviceSearch((device) => {
            dispatch(addDevice(device));
        });
    },
    dependencies: ["bluetoothService"],
};

// ...

store.dispatch(startDeviceScan);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.