Intercepting dependencies in MEF

2019-03-06 14:36发布

问题:

Is it possible to intercept dependency requests in MEF before they get handled by MEF?

This would be useful for implementing decorators and advanced lifetime management.

Something like...

catalogue.AddInterceptor<IExpensiveService>(b => ... return from pool ...);

Or even...

catalogue.AddInterceptor<IExpensiveService>(b => new Decorator(b()));

(where 'b' is the underlying MEF resolution func for resolving the service)

回答1:

Not out of the box, but you can write your own ExportProvider or ComposablePartCatalog implementation to do this.

MefContrib appears to have implemented something like that, take a look at InterceptingCatalog. See also this (possibly outdated) blog post about it.