计算 MEF 容器中的零件数量
我的代码搞砸了 - 我创建了很多短生命周期的对象并使用 MEF 来解决依赖关系。任何有过 MEF 经验的人都知道,MEF 保留着这些人的参考资料。结果是短生命周期变成了 LOOONNNGGG 生命周期。因此,这很容易修复 - 在 CompositionContainer 上使用 SatisfysImportsOnce。
但我现在想让这个 x-check 成为我的单元测试的一部分,这样我就不会意外地将不正确的部分添加到容器中(或者也许我在刚刚进行的代码搜索中错过了一个)。苏...如何做到这一点?
我的代码有点抽象,看起来像这样:
_catalog = new AggregateCatalog();
_container = new CompositionContainer(_catalog);
_batch = new CompositionBatch();
然后我将部件添加到批次中,并调用 _container.Compose(_batch)。我想也许像下面这样的东西可以得到一个计数,但它总是返回零:
int nParts1 = _container.Parts.Count();
int nParts2 = _container.Catalogs.Sum(c => c.Parts.Count());
但是,这两个都返回零。我怎样才能得到这个测试计数?如果性能不是很好也没关系 - 这是测试的一部分,而不是正在运行的应用程序。非常感谢!
I messed up in my code - I create lots of short-lifetime objects and use MEF to resolve dependencies. As anyone with some MEF experience knows, MEF holds onto a reference on these guys. The result is the short lifetime turns into LOOONNNGGG lifetime. So, this is easy enough to fix - use SatisfysImportsOnce on CompositionContainer.
But I'd like to make this x-check part of my unit tests now so that I don't accidently add an incorrect part into the container (or perhaps I missed one in the code search I just did). Sooo... how to do this?
My code, a bit abstracted, looks something like this:
_catalog = new AggregateCatalog();
_container = new CompositionContainer(_catalog);
_batch = new CompositionBatch();
I then add parts to a batch, and call _container.Compose(_batch). I thought perhaps something like the following would work to get a count, but it always returns zero:
int nParts1 = _container.Parts.Count();
int nParts2 = _container.Catalogs.Sum(c => c.Parts.Count());
However, both of those return zero. How can I get this count for tests? It is ok if perf isn't fantastic - this is part of the test, not the running app. Many thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有一个简单的方法可以做到这一点。您需要深入研究 MEF 的内部实现才能找到此信息。由于源代码可用(mef.codeplex.com),这是很有可能的,但仍然不太简单。
There's not a simple way to do this. You'll need to go digging around in the internal implementation of MEF to find this information. Since the source code is available (mef.codeplex.com) this is quite possible, but still not too simple.