@@ -210,6 +210,72 @@ first argument.
210210
211211 .. _resource-provider-wiring-closing :
212212
213+ Scoping Resources using specialized subclasses
214+ ----------------------------------------------
215+
216+ You can use specialized subclasses of ``Resource `` provider to initialize and shutdown resources by type.
217+ Allowing for example to only initialize a subgroup of resources.
218+
219+ .. code-block :: python
220+
221+ class ScopedResource (resources .Resource ):
222+ pass
223+
224+ def init_service (name ) -> Service:
225+ print (f " Init { name} " )
226+ yield Service()
227+ print (f " Shutdown { name} " )
228+
229+ class Container (containers .DeclarativeContainer ):
230+
231+ scoped = ScopedResource(
232+ init_service,
233+ " scoped" ,
234+ )
235+
236+ generic = providers.Resource(
237+ init_service,
238+ " generic" ,
239+ )
240+
241+
242+ To initialize resources by type you can use ``init_resources(resource_type) `` and ``shutdown_resources(resource_type) ``
243+ methods adding the resource type as an argument:
244+
245+ .. code-block :: python
246+
247+ def main ():
248+ container = Container()
249+ container.init_resources(ScopedResource)
250+ # Generates:
251+ # >>> Init scoped
252+
253+ container.shutdown_resources(ScopedResource)
254+ # Generates:
255+ # >>> Shutdown scoped
256+
257+
258+ And to initialize all resources you can use ``init_resources() `` and ``shutdown_resources() `` without arguments:
259+
260+ .. code-block :: python
261+
262+ def main ():
263+ container = Container()
264+ container.init_resources()
265+ # Generates:
266+ # >>> Init scoped
267+ # >>> Init generic
268+
269+ container.shutdown_resources()
270+ # Generates:
271+ # >>> Shutdown scoped
272+ # >>> Shutdown generic
273+
274+
275+ It works using the :ref: `traverse ` method to find all resources of the specified type, selecting all resources
276+ which are instances of the specified type.
277+
278+
213279Resources, wiring, and per-function execution scope
214280---------------------------------------------------
215281
0 commit comments