Quantcast
Channel: patterns & practices: Prism
Viewing all articles
Browse latest Browse all 1878

New Post: Using Prism/MEF Dependency Injection with a plain old class

$
0
0
OK, I answered my own question. It has everything to do with the decorator and how you instantiate 'Class1'. That is, you need to decorate Class1 above with the [Export] attribute, then when you create the object using the CompositionContainer, you'll get the injection to work:
            Class1 instance = compositionContainer.GetExportedValue<Class1>();
The most difficult part was getting a CompositionContainer in the loaded module. For this, I used DI to insert the ServiceLocator in the class when it was built. I have to say that my instincts agree with the article I read calling the static Service Locators the 'Anti-Pattern'. That method of doing things swaps several baked-in dependencies for a single baked-in dependency, but that's another thread. Anyway, the module is initialized with a service locator like so:
        [ImportingConstructor]
        public ModuleA(ILoggerFacade logger, IServiceLocator serviceProvider)
        {
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("serviceProvider");
            }

            this.serviceLocator = serviceProvider as MefServiceLocatorAdapter;
            this.logger = logger;
        }
Then I was able to use it when the module was initialized:
        public void Initialize()
        {
            var compositionContainer = this.serviceLocator.GetInstance<CompositionContainer>();
            var class1 = compositionContainer.GetExportedValue<Class1>();
        }

Viewing all articles
Browse latest Browse all 1878


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>