设置我的依赖注入后,我得到基数不匹配的MEF错误。我相信我正确地从界面导出,当我检查程序时,实际目录是空的。不确定我做错了什么!
容器组成
private static CompositionContainer CreateContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(typeof(IClient).Assembly));
CompositionContainer container = new CompositionContainer(catalog);
return container;
}
创建容器
static void Main(string[] args)
{
CompositionContainer container = CreateContainer();
IClient contactList = container.GetExportedValue<IClient>();
// More code below, but error is happening on the above line
}
客户端导入
namespace MyWcfProgram.WcfProgram
{
[Export(typeof(IClient))]
public class Client : IClient
{
private readonly ILogic contactLogic;
[ImportingConstructor]
public Client([Import] ILogic contactLogic)
{
if(contactLogic == null)
{
throw new Exception();
} else
{
this.contactLogic = contactLogic;
}
}
// MORE BELOW LEFT OUT
}
逻辑导入
namespace MyWcfProgram.Logic
{
[Export(typeof(ILogic))]
public class Logic : ILogic
{
private readonly IData dataAccess;
[ImportingConstructor]
public Logic([Import] IData dataAccess)
{
if (dataAccess == null)
{
throw new Exception();
}
this.dataAccess = dataAccess;
}
Data.cs
namespace MyWcfProgram.Data
{
[Export(typeof(IData))]
public class Data : IData
{
private string connectionString = "CONNECTION STRING IS HERE";
private System.Data.SqlClient.SqlConnection myconnection = new System.Data.SqlClient.SqlConnection();
// More code below, but no constructor since there are no dependencies
}
答案 0 :(得分:0)
我知道你没有问过这个但是如果你对MEF没有硬性依赖,我可能会建议使用SimpleInjector。 MEF已经过时了,如果您只需要一个IOC框架,那么使用SimpleInjector可以让您的生活更加美好。
容器组成
private static Container CreateContainer()
{
var container = new Container();
container.Register<IClient, MyWcfProgram.WcfProgram.Client>();
container.Register<ILogic, MyWcfProgram.Logic.Logic>();
container.Register<IData, MyWcfProgram.Data.Data>();
return container;
}
创建容器
static void Main(string[] args)
{
var container = CreateContainer();
IClient contactList = container.GetExportedValue<IClient>();
// More code below, but error is happening on the above line
}
客户端导入
namespace MyWcfProgram.WcfProgram
{
public class Client : IClient
{
private readonly ILogic contactLogic;
public Client(ILogic contactLogic)
{
if(contactLogic == null)
{
throw new Exception();
} else
{
this.contactLogic = contactLogic;
}
}
// MORE BELOW LEFT OUT
}
逻辑导入
namespace MyWcfProgram.Logic
{
public class Logic : ILogic
{
private readonly IData dataAccess;
public Logic(IData dataAccess)
{
if (dataAccess == null)
{
throw new Exception();
}
this.dataAccess = dataAccess;
}
<强> Data.cs 强>
namespace MyWcfProgram.Data
{
public class Data : IData
{
private string connectionString = "CONNECTION STRING IS HERE";
private System.Data.SqlClient.SqlConnection myconnection = new System.Data.SqlClient.SqlConnection();
// More code below, but no constructor since there are no dependencies
}