How does Import and Export work at Runtime in MEF?
I am starting to learn, MEF and one important thing in it is that I can mark some item (class, propety,method) with Export attribute so that, who ever wants use it will create Import attribute on an instance varaible and use it. How does this mapping happen and when does it happen? Is the import happen lazily on demand or all the composition happen at the start 开发者_运维知识库up? Sorry for the ignorant question, I am trying to understand the flow.
It happens in a phase called "Composition". First you create a container and load all your possible sources of parts into it, and then you Compose
it. When you do the composition, it resolves all the dependencies and throws an exception if it can't resolve them all properly.
In general, your parts get instantiated during composition (and if you set a break point in the constructor of your part classes, you will see the break point hit during your call to Compose()
). However, you can override this in a straightforward way if you use Lazy<T>
as the type of your import (assuming you exported your part as type T
).
To see how the composition works, take a look at the Compose()
method here.
精彩评论