Microsoft.Composition (Portable MEF): Scoping
This post is part of mini series, which complete the full MEF series.
This post will go over Microsoft.Composition Scoping.
What is IoC scoping?
IoC scoping is the ability to control the lifetime of registration
per specific execution scope. whatever resolved in the scope can resolve
it’s item that register under the scope or at its parent container.
Classic example for such scope is request.
You may want to resolve the same instance again and again within
the request scope while keeping it completely isolated from other requests.
When supporting this kind of scope you can use the IoC safely without
potential side effects.
How to register scope with Portable MEF?
The topology for this sample will be a process which will resolve
request object (under a scope).
Each Request will resolve :
– Global object (which register as singleton)
– Items (which register under a scoped lifetime).
The Global object will have the same Id all over the execution (singleton)
while the Item will be the same under the request boundary, but different between requests.
The output of the sample I’m going to present will look like
the following snapshot (while the Id represent the instantiation):
let see some code.
We register 4 different types, IProcess and IGlobal as shared (singleton).
IRequest and IItemPerRequest as Shared which get a scope name “Request” (lines 10, 13).
On lines (19-23) we resolve the process and calling Execute:
the following snippet is the Process class:
The scope (Request) must be declare as ExportFactory<T> (line 8) and it’s should be decorated
with the [SharingBoundary] attribute that match the registered scope (line 7).
This snippet is using 2 scoped request (lines 14-19 and 21-26).
Each request will resolve different instance (if the type registered for the scope).
The next snippet show the Request class.
Both properties, ItemPeeRequestA and ItemPeeRequestB will get the same instance lines 17-20).
finally the code for the ItemPerRequest is:
Because it’s sharing the same scope with the request object, it can resolve the request instance.
this sample is fierily simplified but it suggesting the power of IoC scoping.
Other IoC also support scoping and I will write about it on future post.