我查看了其他一些谈论使用的帖子:
[ImportMany]
IEnumerable<IPlugin> plugins;
但在我的情况下,它不是一个集合。
请参阅下面的代码和错误消息:
[Export(typeof(ITransactionActionMasterDao))]
public class TransactionActionMasterDao : BaseDao, ITransactionActionMasterDao
public abstract class BaseTransactionGenerator : ITransactionGenerator
{
[Import(typeof(ITransactionActionMasterDao))]
private ITransactionActionMasterDao transactionActionMasterDao;
public BaseTransactionGenerator()
{
//Grab all the assemblies in the current folder
AggregateCatalog catalog = new AggregateCatalog(new AssemblyCatalog( typeof(TransactionActionMasterDao).Assembly) );
CompositionContainer container = new CompositionContainer(catalog);
// This will set the fields (aka execute the [Import])
**//below line getting error**
container.ComposeParts(this);
}
}
public class ManualTransactionGenerator : BaseTransactionGenerator
{
public ManualTransactionGenerator():base()
{
}
}
ManualTransactionGenerator和BaseTransactionGenerator都在同一个C#类库项目中。
TransactionGeneratorsIntegrationTest存在于另一个UnitTest项目中
public class TransactionGeneratorsIntegrationTest
{
[TestMethod]
public void IT_GenerateManualTransactions()
{
ManualTransactionGenerator generator = new ManualTransactionGenerator()
}
}
错误讯息: 该组合物产生单一组成误差。根本原因如下。查看CompositionException.Errors属性以获取更多详细信息。
1)找到多个与约束匹配的导出: ContractName HL.DataAccess.Adjustment.Contracts.DataAccessObjects.ITransactionActionMasterDao RequiredTypeIdentity HL.DataAccess.Adjustment.Contracts.DataAccessObjects.ITransactionActionMasterDao
更新
我们改变了设计,新代码看起来像这样
[Export(typeof(ITransactionActionMasterDao))]
public class TransactionActionMasterDao : BaseDao, ITransactionActionMasterDao
[Export(typeof(ITransactionActionMasterDao))]
public class CustomerTransactionActionMasterDao : BaseDao, ITransactionActionMasterDao
public abstract class BaseTransactionGenerator : ITransactionGenerator
{
[Import(typeof(ITransactionActionMasterDao))]
private ITransactionActionMasterDao transactionActionMasterDao;
public BaseTransactionGenerator()
{
**//Below lines will throw error**
AggregateCatalog catalog = new AggregateCatalog(new AssemblyCatalog( typeof(TransactionActionMasterDao).Assembly),
new AssemblyCatalog( typeof(CustomerTransactionActionMasterDao ).Assembly) );
**//This is correct. We need to add ONLY one. Not both**
AggregateCatalog catalog = new AggregateCatalog(new AssemblyCatalog( typeof(TransactionActionMasterDao).Assembly);
CompositionContainer container = new CompositionContainer(catalog);
// This will set the fields (aka execute the [Import])
**//below line getting error**
container.ComposeParts(this);
}
}
这解决了我们的问题。
答案 0 :(得分:0)
您可能遇到并排加载包含[Export]
属性的程序集的多个版本的问题。要测试这个理论,请尝试以下方法:
[Import]
更改为[ImportMany]
。如果(何时)您在列表中观察到多个项目,请检查每个实例以确定其加载的程序集的位置。
transactionActionMasterDao[i].GetType().Assembly.Location
如果是这种情况,您可能需要使用程序集绑定重定向来确保只加载包含导出的程序集的一个副本。