Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用mef2注入包含注入模块的模块_C#_Design Patterns_Dependency Injection_Windows Services_Mef - Fatal编程技术网

C# 使用mef2注入包含注入模块的模块

C# 使用mef2注入包含注入模块的模块,c#,design-patterns,dependency-injection,windows-services,mef,C#,Design Patterns,Dependency Injection,Windows Services,Mef,我有一个windows服务,正在向其中注入一个模块: private ICoupon _couponManager; ... DirectoryCatalog catalog = new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins")); _container = new CompositionContainer(catalog); _couponManager = _containe

我有一个windows服务,正在向其中注入一个模块:

private ICoupon _couponManager;
...
DirectoryCatalog catalog = new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins"));
_container = new CompositionContainer(catalog);
_couponManager = _container.GetExportedValue<ICoupon>();// Here I'm getting an exception
因此,我得到了“尝试创建'X.Business.CouponManager'类型的实例时发生异常”错误。我必须如何注入我的模块

我不确定我的问题是否清楚,如果不清楚,请询问细节

提前感谢,


编辑:有趣的是:我可以将这个模块注入到我的asp.NETMVC应用程序中,并毫无问题地使用它

除非我没有从您的问题中了解到一些业务需求,否则CouponManager不需要拥有自己的CompositionContainer,也不需要组成它的各个部分

当你打电话的时候

_couponManager = _container.GetExportedValue<ICoupon>();
\u couponManager=\u container.GetExportedValue();
它将构成优惠券管理器的一个实例。执行此操作时,它将自动合成其所有导入(在本例中为IWallet),然后递归合成其所有子导入

因此,如果IWallet也有导入,那么它们也将在对

_couponManager = _container.GetExportedValue<ICoupon>();
\u couponManager=\u container.GetExportedValue();
因此,除非您需要为您的钱包准备一个单独的容器,否则我会在CouponManager中删除该容器,并删除其容器中的内容


然后我会再次尝试,看看这是否解决了您的异常。

除了Gilles回答之外,您的类应该是这样的

[Export(typeof(ICoupon))]
public class CouponManager : ICoupon 
{
  private IWallet _iWallet;

  [ImportingConstructor]
  public CouponManager(IWallet iwallet)
  {
     this._iWallet= iwallet;
  }
}

关于你的建议,我修改了代码,但仍然得到同样的例外。你还有其他见解吗?我试过你的建议,但还是得到同样的例外。您还有其他见解吗?在调用GetExportedValue之前调试容器。我假设您只是拥有插件文件夹中的依赖项,而错过了应用文件夹中的一些依赖项。您的容器在导出时必须具有ICOON和IWallet导出!我不同意你们班的“应该”是这样的。虽然我认为在大多数情况下,导入构造函数是比在属性上使用导入更好的选择,但两者都是完全有效的,在正常情况下都可以工作。@Giles我想这可以归结为构造函数与属性注入在隐藏依赖项方面的不同。我发现了属性注入的用法,虽然它看起来更简单,但它确实隐藏了您类型的需求。如果现在忽略MEF/DI部分并考虑一般用途,如果您没有通过构造函数来表示依赖关系,那么其他人如何知道您需要正确使用类型,以及如何使用“代码>新CoupNoMungor())/<代码>在可用状态下创建类型的实例?
[Export(typeof(ICoupon))]
public class CouponManager : ICoupon 
{
  private IWallet _iWallet;

  [ImportingConstructor]
  public CouponManager(IWallet iwallet)
  {
     this._iWallet= iwallet;
  }
}