82762

Prism ServiceLocator GetInstance and MEF

Question:

I'm trying to use Microsoft.Practices.ServiceLocation.ServiceLocator and MEF. Interface IServiceLocator defines method GetInstance with two parameters. First parameter is serviceType and second paremeter is key.

I have two classes which implement interface IMyInterface and they have Export attribute: [Export(typeof(IMyInterface)), PartCreationPolicy(CreationPolicy.Shared)] public class Class1 : IMyInterface {} [Export(typeof(IMyInterface)), PartCreationPolicy(CreationPolicy.Shared)] public class Class2: IMyInterface {}

I want to get instance of Class1 via Prism ServiceLocator GetInstance method:

ServiceLocator.Current.GetInstance(typeof(IMyInterface),"Key");

But I have no idea how and where should be "key" defined. I tried to define key in export attribute:

[Export("Key1",typeof(IMyInterface)), PartCreationPolicy(CreationPolicy.Shared)] public class Class1 : IMyInterface {} [Export("Key2",typeof(IMyInterface)), PartCreationPolicy(CreationPolicy.Shared)] public class Class2: IMyInterface {}

When I call method GetInstance with key parameter

ServiceLocator.Current.GetInstance(typeof(IMyInterface),"Key1");

I get Microsoft.Practices.ServiceLocation.ActivationException (Activation error occured while trying to get instance of type IMyInterface, key "Key1"). Does anybody know how can be the export key defined? Thanks

Answer1:

Prism uses MefServiceLocatorAdapter to adapt MEF's CompositionsContainer to the IServiceLocator interface. This is the actual code that is used by it to get your part:

protected override object DoGetInstance(Type serviceType, string key) { IEnumerable<Lazy<object, object>> exports = this.compositionContainer.GetExports(serviceType, null, key); if ((exports != null) && (exports.Count() > 0)) { // If there is more than one value, this will throw an InvalidOperationException, // which will be wrapped by the base class as an ActivationException. return exports.Single().Value; } throw new ActivationException( this.FormatActivationExceptionMessage(new CompositionException("Export not found"), serviceType, key)); }

So as you can see, you're exporting and calling GetInstance correctly. However, I believe your service locator isn't set up correctly, and that's why you're getting this exception. If you're using Prism's MefBootstrapper to initialize your application, this should already be done for you. Otherwise, you'll need to use this code to initialize it:

IServiceLocator serviceLocator = new MefServiceLocatorAdapter(myCompositionContainer); ServiceLocator.SetLocatorProvider(() => serviceLocator);

Recommend

  • MVVM WPF change smoothly one window to another
  • Xamarin CarouselView Not Displayed
  • What's a Silverlight plugin?
  • Xamarin forms Prism how can I use IEventAggregator in iOS project
  • Retrieve value from csv file and replace it in database in C#
  • Spring boot: apply @Configuration to certain package only
  • How do I enable a submit button if 1 or more checkboxes are checked?
  • python: list modules within the package
  • How to display formatted HTML data in kendo ui grid column
  • Deserialize array of objects inside another object using Gson
  • “find all references” does not work unless dependent files are open
  • C# Delegate problem - what the heck does this code do?
  • instance of class held by composition container in mef
  • My TextBox added programmatically in code behind After Page reload losess values. Is there any way t
  • Pass a custom comparator through a function
  • Cannot change class variables with multiprocessing.Process object in Python3
  • Build Matrix of Comparisons in SQl Server
  • What is ./.local/share/Trash (Unix) [closed]
  • Query pkg-config variable through autotools
  • Scala: Function returning an unknown type
  • C# List of Panels
  • Error in installing package: fatal error: stdlib.h: no such file or directory
  • Is there a way to save the selected text and highlight it again once the page is refreshed?
  • Refering to the class itself from within a class mehod in Objective C
  • Exception “firebase.functions() takes … no argument …” when specifying a region for a Cloud Function
  • Highlight one bar in a series in highcharts?
  • ilmerge with a PFX file
  • Why value captured by reference in lambda is broken? [duplicate]
  • How would I use PHP exceptions to define a redirect?
  • To display the title for the current loaction in map in iphone
  • Calling of Constructors in a Java
  • Invalid access key error using credentials redeemed from an amazon open id token
  • PHP: When would you need the self:: keyword?
  • InvalidAuthenticityToken between subdomains when logging in with Rails app
  • Acquiring multiple attributes from .xml file in c#
  • Why joiner is not used after Sequence generator or Update statergy
  • Recursive/Hierarchical Query Using Postgres
  • reshape alternating columns in less time and using less memory
  • UserPrincipal.Current returns apppool on IIS
  • How can I use threading to 'tick' a timer to be accessed by other threads?