这是我的表单,它应该显示我导入的类的结果:
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'(托管(v4.0.30319)):已加载
'C:\的Windows \组件\ GAC_MSIL \ Microsoft.VisualStudio.DebuggerVisualizers \ 11.0.0.0__b03f5f7f11d50a3a \ Microsoft.VisualStudio.DebuggerVisualizers.dll' 该组合物产生单一组成误差。根本原因是 提供如下。查看CompositionException.Errors属性 更详细的信息。
1)导出'WindowsFormsApplication1.Template + Tests + Example.Result(ContractName =“ClassLibrary1.ITests”)'不能分配给'ClassLibrary1.ITests'类型。
导致:无法设置导入 “WindowsFormsApplication1.Form1.Template (ContractName =“ClassLibrary1.ITests”)'部分 'WindowsFormsApplication1.Form1'。元件: WindowsFormsApplication1.Form1.Template (ContractName =“ClassLibrary1.ITests”) - > WindowsFormsApplication1.Form1
答案 0 :(得分:3)
看起来您将[Export]
放在了错误的位置。您正尝试导出Result
这是一个类型为ITests的字符串。相反,导出应该是您的班级级别:
[Export(typeof(ITests))]
public class Example : ITests
{
public string Result(string res)
{
string resa = res + " dit is door de test gegaan";
return resa;
}
}