xkcd
xkcd

Reputation: 2590

Injecting a module that contains an injected module using mef2

I have a windows service and I'm injecting a module to it:

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

But the module that I'm trying to import is an constructer injected module:

[Import(typeof(IWallet))]
private IWallet _iWallet;

private static CompositionContainer _container;

public CouponManager()
{
    DirectoryCatalog catalog = new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins"));
    _container = new CompositionContainer(catalog);
    _container.ComposeParts();
}

So I'm getting "An exception occurred while trying to create an instance of type 'X.Business.CouponManager'." error. How do I have to inject my module?

I'm not sure if my question is clear, if not please ask for details.

Thanks in advance,

Edit: The interesting part is: I can inject this module to my asp.net mvc application and use it without problem.

Upvotes: 0

Views: 406

Answers (2)

blindmeis
blindmeis

Reputation: 22445

in addition to Gilles answer your class should look like this

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

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

Upvotes: 1

Gilles
Gilles

Reputation: 5407

Unless there is some business need I haven't grasped from your question, there is no need for CouponManager to have it's own CompositionContainer and for it to compose it's parts.

When you call

_couponManager = _container.GetExportedValue<ICoupon>();

It will compose an instance of your coupon manager. While doing so it will automatically compose all of it's imports (in this case, your IWallet) and then recursively compose all of their child imports.

Thus, if IWallet also has imports, they will also be composed in the initial call to

_couponManager = _container.GetExportedValue<ICoupon>();

So unless you need to have a seperate container for your wallet, I would remove the container in CouponManager and remove the composing in it's container.

Then I would try again to see if that resolves your exception.

Upvotes: 1

Related Questions