di usage in website
This commit is contained in:
64
apps/website/lib/di/providers/ContainerProvider.tsx
Normal file
64
apps/website/lib/di/providers/ContainerProvider.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, ReactNode, useContext, useMemo } from 'react';
|
||||
import { Container } from 'inversify';
|
||||
import { createContainer } from '../container';
|
||||
|
||||
export const ContainerContext = createContext<Container | null>(null);
|
||||
|
||||
interface ContainerProviderProps {
|
||||
children: ReactNode;
|
||||
/**
|
||||
* Optional container instance (for testing or custom configuration)
|
||||
*/
|
||||
container?: Container;
|
||||
/**
|
||||
* Create scoped container for request/session isolation
|
||||
*/
|
||||
scoped?: boolean;
|
||||
}
|
||||
|
||||
export function ContainerProvider({
|
||||
children,
|
||||
container: providedContainer,
|
||||
scoped = false
|
||||
}: ContainerProviderProps) {
|
||||
const container = useMemo(() => {
|
||||
if (providedContainer) {
|
||||
return providedContainer;
|
||||
}
|
||||
|
||||
const rootContainer = createContainer();
|
||||
// Note: This version doesn't support child containers, so scoped just returns root
|
||||
return rootContainer;
|
||||
}, [providedContainer, scoped]);
|
||||
|
||||
return (
|
||||
<ContainerContext.Provider value={container}>
|
||||
{children}
|
||||
</ContainerContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to access the container directly
|
||||
*/
|
||||
export function useContainer(): Container {
|
||||
const container = useContext(ContainerContext);
|
||||
if (!container) {
|
||||
throw new Error('useContainer must be used within ContainerProvider');
|
||||
}
|
||||
return container;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to get a scoped container for request isolation
|
||||
* (In this version, returns root container)
|
||||
*/
|
||||
export function useScopedContainer(): Container {
|
||||
const rootContainer = useContainer();
|
||||
return useMemo(() => {
|
||||
// Return new container for isolation
|
||||
return new Container();
|
||||
}, [rootContainer]);
|
||||
}
|
||||
Reference in New Issue
Block a user