I currently have the following constructors in my viewmodel
public CartViewModel() : this(new PayPalCompleted()) { }
public CartViewModel(IPayPalCompleted serviceAgent)
{
if (!IsDesignTime)
{
_ServiceAgent = serviceAgent;
WireCommands();
}
}
I am trying to modularise my application Prism and MEF. My modules work fine but I'm having trouble with one of my viewmodels.
My problem is that I need to import the EventAggregator at the constructor but I'm having issues about how I do this with a paramaterless constructor as well as an importing constructor
[ImportingConstructor]
public CartViewModel([Import] IEventAggregator eventAggregator)
{
if (!IsDesignTime)
{
_ServiceAgent = new PayPalCompleted();
TheEventAggregator = eventAggregator;
WireCommands();
}
}
ie I want to do something like this
public CartViewModel() : this(new PayPalCompleted(), IEventAggregator eventAggregator) { }
[ImportingConstructor]
public CartViewModel(IPayPalCompleted serviceAgent, IEventAggregator eventAggregator)
{
...stuff
}
Which isn't correct I know... what is??
Part of the issue, I think, is that when using an importing constructor then the parameters in the constructor are import parameters by default - which would mean that they need a corresponding export for MEF to be able to compose correctly. Which probably means I should export my paypay service? Or should it?
Thanks
The easiest way to deal with this is to expose a property of type IEventAggregator, implement IPartImportsSatisifiedNotification and handle event subscriptions in that method.
Something like this
public class CartViewModel : IPartImportsSatisfiedNotification
{
private readonly IPayPalCompleted _serviceAgent;
public CartViewModel(IPayPalCompleted serviceAgent)
{
this._serviceAgent = serviceAgent;
CompositionInitializer.SatisfyImports(this);
}
[Import]
public IEventAggregator EventAggregator { get; set; }
void IPartImportsSatisfiedNotification.OnImportsSatisifed()
{
if (EventAggregator != null)
{
// Subscribe to events etc.
}
}
}