Skip to content

Instantly share code, notes, and snippets.

@tswistak
Created May 8, 2019 15:51
Show Gist options
  • Save tswistak/ea9d7a1eb3ce81b2302e41e5a0f27ff1 to your computer and use it in GitHub Desktop.
Save tswistak/ea9d7a1eb3ce81b2302e41e5a0f27ff1 to your computer and use it in GitHub Desktop.
InversifyJS with React Hooks, listing 4
import React, { useContext } from 'react';
import { Container, interfaces } from 'inversify';
const InversifyContext = React.createContext<{ container: Container | null }>({ container: null });
type Props = {
container: Container;
};
export const Provider: React.FC<Props> = (props) => {
return (
<InversifyContext.Provider value={{ container: props.container }}>
{props.children}
</InversifyContext.Provider>
);
};
export function useInjection<T>(identifier: interfaces.ServiceIdentifier<T>) {
const { container } = useContext(InversifyContext);
if (!container) { throw new Error(); }
return container.get<T>(identifier);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment