MEF合成错误,导出不能正常工作
本文关键字:常工作 工作 不能 错误 MEF | 更新日期: 2023-09-27 18:01:30
这是我的表单,它应该显示从我导入的类的结果:
public partial class Form1 : Form
{
[Import(typeof(ITests))]
public ITests Template;
public string texter;
public Form1()
{
InitializeComponent();
texter = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "''bin''dll";
textBox1.Text = texter;
string[] array = Directory.GetFiles(texter, "*.dll");
foreach(string file in array)
{
textBox1.Text += Environment.NewLine + file;
}
Program();
}
public void Program()
{
AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new DirectoryCatalog(texter));
Console.WriteLine(catalog.Catalogs);
try
{
CompositionContainer container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
这是我的公共接口:我已经在两个项目中导入了它们,所以我已经尝试避免汇编引用错误
namespace ClassLibrary1
{
public interface ITests
{
string Result(string result);
}
}
这是我的DLL与导出代码:
namespace WindowsFormsApplication1
{
public class Template
{
//Please write all your tests in this class
//[TestClass]
public class Tests
{
//example of class
//[TestMethod]
public class Example : ITests
{
[Export(typeof(ITests))]
public string Result(string res)
{
string resa = res + " dit is door de test gegaan";
return resa;
}
}
//[TestMethod]
public class ExampleTest2
{
}
}
}
}
我得到这个错误:
类型的第一次机会异常"System.ComponentModel.Composition.Primitives.ComposablePartException"发生在System.ComponentModel.Composition.dll中'WindowsFormsApplication1.vshost.exe' (Managed (v4.0.30319)): Loaded" C: ' Windows '会议' GAC_MSIL ' Microsoft.VisualStudio.DebuggerVisualizers ' 11.0.0.0__b03f5f7f11d50a3a ' Microsoft.VisualStudio.DebuggerVisualizers.dll"这篇作文产生了一个写作错误。根本原因是下面提供。检查CompositionException。的Errors属性更详细的信息
1)导出"WindowsFormsApplication1.Template+Tests+Example"。结果(ContractName="ClassLibrary1.ITests")'不能赋值给类型'ClassLibrary1.ITests'.
导致:无法设置导入"WindowsFormsApplication1.Form1.Template(ContractName=" classlibrary . itests ")'"WindowsFormsApplication1.Form1"。元素:WindowsFormsApplication1.Form1.Template(ContractName = " ClassLibrary1.ITests")——>WindowsFormsApplication1。Form1
看起来你把[Export]
放在了错误的地方。您正在尝试导出Result
,这是一个字符串类型ittests。相反,导出应该位于您的类级别:
[Export(typeof(ITests))]
public class Example : ITests
{
public string Result(string res)
{
string resa = res + " dit is door de test gegaan";
return resa;
}
}