c# - mefcontrib拦截目录导出错误

标签 c# asp.net-mvc mef

我正在尝试在 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/

相关文章:

c# - C# 中的 SafeFileHandle 是什么,我应该在什么时候使用它?

asp.net-mvc - 如何在进入 Controller 操作之前从用户友好的 url 中删除不必要的信息

c# - 如何创建将在子目录中搜索插件的 DirectoryCatalog

wpf - 如何在 View 模型中使用 Mef 容器解析 View

c# - Dictionary.Contains键比较

c# - 如何将接口(interface)与实现分离

c# - 未找到 Assets XNA

javascript - jQuery 通过 Ajax 在 ASP.NET MVC C# 中调用 Action 方法

c# - Asp.NET MVC 应用程序上的 MySQLRoleProvider 错误但仅使用 SQLServer

c# - 使用由 MEF 加载的模型类型的 ASP.Net MVC View 导致 View 构建器中的 JIT 编译错误