我正在尝试在 asp.net mvc2 应用程序中测试 mef 和 mefcontrib,但出现错误:
Cannot cast the underlying exported value of type LoggerExtSys.Domain.WebLogger
(ContractName="LoggerExtSys.Domain.IWebLogger") to type LoggerExtSys.Domain.IWebLogger.
我的测试项目here
Global.asax 中的代码:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
var catalog = new CatalogBuilder()
.ForAssembliesInDirectory(HttpRuntime.BinDirectory, "*ExtSys.dll")
.Build();
// Create interception configuration
var cfg = new InterceptionConfiguration()
.AddInterceptor(new StartableStrategy());
// Create the InterceptingCatalog with above configuration
var interceptingCatalog = new InterceptingCatalog(catalog, cfg);
// Create the container
var container = new CompositionContainer(interceptingCatalog);
// exception here
var barPart = container.GetExportedValue<IWebLogger>();
barPart.Debug("Test");
}
当我尝试获取 GetExportedValue 时出现异常
WebLogger 中的代码:
[Export(typeof(IWebLogger))]
public class WebLogger : IWebLogger
{
#region IWebLogger Members
public void Debug(string str)
{
}
#endregion
#region ICoreExtension Members
public void Initialize()
{
}
#endregion
}
但在桌面应用程序中一切正常。 如何解决?感谢大家
最佳答案
好的,问题出在加载程序集的代码块中:
public AggregateCatalog ForAssembliesInDirectory(string directory, string pattern)
{
IList<ComposablePartCatalog> _catalogs = new List<ComposablePartCatalog>();
var dir = new DirectoryInfo(directory);
Assembly assembly;
foreach (var file in dir.GetFiles(pattern))
{
assembly = Assembly.LoadFile(file.FullName);
_catalogs.Add(new AssemblyCatalog(assembly));
}
return new AggregateCatalog(_catalogs);
}
在所有测试之后,我将其删除并使用 DirectoryCatalog。我不知道为什么,但它在桌面和网络应用程序中工作。 谁能告诉我为什么我的旧代码不能在网络应用程序中工作会得到接受的答案和 50 赏金。谢谢大家
关于c# - mefcontrib拦截目录导出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7427666/