4

I'm using C# 6.0, WPF 4.5.2 and the PRISM-architecture 6.2.x (Unity). And I'm using a class derived from Canvas.

So, there is a class MyCanvas, which is used in a UserControl (XAML) in the way of:

<Usercontrol [...]>
 <mycontrols:MyCanvas [...] />
</Usercontrol>

This works fine, but what I need to do, is to inject the Eventaggregator to the implementation of the MyCanvas-class.

The XAML seems to only call the static constructor, but I need to store the reference to the Eventaggregator.

How can I do that?

Thanks in advance.

Elex
  • 67
  • 2
  • 7
  • You can use ServiceLocator pattern(or anti-pattern?), if you cannot inject your dependency in constructor. – 3615 Nov 17 '16 at 10:52
  • Indeed you could use a ServiceLocator but maybe you should consider using the DataContext and viewmodels to do the injection instead. Here a related question which could help: http://stackoverflow.com/questions/25366291/how-to-handle-dependency-injection-in-a-wpf-mvvm-application – LeBaptiste Nov 17 '16 at 11:03
  • 2
    Thanks for the help guys! But with the ServiceLocator the problems remains the same - how can I use the ServiceLocator without DI? AND I WANT TO use DI. I my understanding, it doesn't make much sense, to go off-pattern everytime a problem comes along. Because if I did so, I wouldn't use any pattern at all, which means, that I don't have any improvement. – Elex Nov 18 '16 at 09:59

1 Answers1

4

Try using the service locator.

var eventAgg = ServiceLocator.Current.GetInstance<IEventAggregator>();
Connell.O'Donnell
  • 3,603
  • 11
  • 27
  • 61
  • 3
    Service-Locator is an anti-pattern because you're hardcoding a reference to a static object or static-state - and makes it very difficult (if not impossible) to control ViewModel lifetime or support multiple concurrent views/windows with ViewModels of the same type. – Dai Apr 30 '21 at 13:08