Factories in MEF

Feb 25, 2009 at 8:42 AM
I found the way introducing part factories within the "MefShapes" sample.
I clearly understand why "ShapeFactory.cs" exists and what it does, however I wonder wether it will be any "less steps" solutions in future versions in order to create a new object each time GetExportedObject is called? I have a feeling that most of the developers will start hating current approach soon :)
Feb 25, 2009 at 4:24 PM

Hi Denis,

Instead of using ICompositionService, you can add the container as an ExportProvider to itself and [Import] it into a class like ShapeFactory. Admittedly there are just as many steps involved overall, but the ShapeFactory can be simplified to (approximately!):

    [Export]

    public class ShapeFactory

    {

        private readonly Random random = new Random((int)DateTime.Now.Ticks);

        [Import]

        private ExportProvider ExportProvider { get; set; }

        public IShape GetRandomShape()

        {

            var possibleShapes = ExportProvider.GetExports<IShape>().ToArray();

            int randomIndex = random.Next(possibleShapes.Count);

            return possibleShapes[randomIndex].GetExportedObject();

        }

    }

There’s an similar example with a few tweaks called ‘ControllerProvider’ in the source code at: http://cid-668630fe3ecd2791.skydrive.live.com/self.aspx/.Public/InjectedContext.zip. (From http://blogs.msdn.com/nblumhardt/archive/2008/12/27/container-managed-application-design-prelude-where-does-the-container-belong.aspx).

Hope this helps,

Nick

From: DenisVuyka [mailto:notifications@codeplex.com]
Sent: Wednesday, February 25, 2009 1:42 AM
To: Nicholas Blumhardt
Subject: Factories in MEF [MEF:48466]

From: DenisVuyka

I found the way introducing part factories within the "MefShapes" sample.

I clearly understand why "ShapeFactory.cs" exists and what it does, however I wonder wether it will be any "less steps" solutions in future versions in order to create a new object each time GetExportedObject is called? I have a feeling that most of the developers will start hating current approach soon :)

Read the full discussion online.

To add a post to this discussion, reply to this email (MEF@discussions.codeplex.com)

To start a new discussion for this project, email MEF@discussions.codeplex.com

You are receiving this email because you subscribed to this discussion on CodePlex. You can unsubscribe or change your settings on codePlex.com.

Please note: Images and attachments will be removed from emails. Any posts to this discussion will also be available online at codeplex.com

Feb 25, 2009 at 7:23 PM
Magic! Everything works perfect!
I got rid of private Retreiver classes and used your approach. I should find out that way myself :)
Thanks for your help