Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7889023
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T05:59:21+00:00 2026-06-03T05:59:21+00:00

Consider the following existing classes which uses MEF to compose Consumer . public interface

  • 0

Consider the following existing classes which uses MEF to compose Consumer.

public interface IProducer
{
    void Produce();
}

[Export(typeof(IProducer))]
public class Producer : IProducer
{
    public Producer()
    {
        // perform some initialization
    }

    public void Produce()
    {
        // produce something
    }
}

public class Consumer
{
    [Import]
    public IProducer Producer
    {
        get;
        set;
    }

    [ImportingConstructor]
    public Consumer(IProducer producer)
    {
        Producer = producer;
    }

    public void DoSomething()
    {
        // do something
        Producer.Produce();
    }
}

However, the creation of Producer has become complex enough that it can no longer be done within the constructor and the default behavior no longer suffices.

I’d like to introduce a factory and register it using a custom FactoryAttribute on the producer itself. This is what I have in mind:

[Export(typeof(IProducer))]
[Factory(typeof(ProducerFactory))]
public class Producer : IProducer
{
    public Producer()
    {
        // perform some initialization
    }

    public void Produce()
    {
        // produce something
    }
}

[Export]
public class ProducerFactory
{
    public Producer Create()
    {
        // Perform complex initialization
        return new Producer();
    }
}

public class FactoryAttribute : Attribute
{
    public Type ObjectType
    {
        get;
        private set;
    }

    public FactoryAttribute(Type objectType)
    {
        ObjectType = objectType;
    }
}

If I had to write the “new” code myself, it may very well look as follows. It would use the factory attribute, if it exists, to create a part, or default to the MEF to create it.

public object Create(Type partType, CompositionContainer container)
{
    var attribute = (FactoryAttribute)partType.GetCustomAttributes(typeof (FactoryAttribute), true).FirstOrDefault();
    if (attribute == null)
    {
        var result = container.GetExports(partType, null, null).First();
        return result.Value;
    }
    else
    {
        var factoryExport = container.GetExports(attribute.ObjectType, null, null).First();
        var factory = factoryExport.Value;
        var method = factory.GetType().GetMethod("Create");
        var result = method.Invoke(factory, new object[0]);
        container.ComposeParts(result);
        return result;
    }
}

There are a number of articles how to implement a ExportProvider, including:

  1. MEF + Object Factories using Export Provider
  2. Dynamic Instantiation

However, the examples are not ideal when

  1. The application has no dependencies or knowledge of Producer, only IProducer. It would not be able to register the factory when the CompositionContainer is created.
  2. Producer is reused by several applications and a developer may mistakenly forget to register the factory when the CompositionContainer is created.
  3. There are a large number of types that require custom factories and it may pose a maintenance nightmare to remember to register factories when the CompositionContainer is created.

I started to create a ExportProvider (assuming this would provide the means to implement construction using factory).

public class FactoryExportProvider : ExportProvider
{
    protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition,
                                                          AtomicComposition atomicComposition)
    {
        // What to do here? 
    }
}

However, I’m having trouble understanding how to tell MEF to use the factory objects defined in the FactoryAttribute, and use the default creation mechanism if no such attribute exists.

What is the correct manner to implement this? I’m using MEF 2 Preview 5 and .NET 4.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T05:59:23+00:00Added an answer on June 3, 2026 at 5:59 am

    You can make use of a property export:

    public class ProducerExporter
    {
       [Export]
       public IProducer MyProducer
       {
           get
           {
               var producer = new Producer();
               // complex initialization here
               return producer;
           }
       }
    }
    

    Note that the term factory isn’t really appropriate for your example, I would reserve that term for the case where the importer wants to create instances at will, possibly by providing one or more parameters. That could be done with a method export:

    public class ProducerFactory
    {
       [Export(typeof(Func<Type1,Type2,IProducer>)]
       public IProducer CreateProducer(Type1 arg1, Type2 arg2)
       {
           return new Producer(arg1, arg2);
       }
    }
    

    On the import side, you would then import a Func<Type1,Type2,IProducer> that you can invoke at will to create new instances.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider following example : public class SomeBusinessLayerService : DataService<MyEntityContainer> { [WebInvoke] void DoSomething(string someParam)
Consider following program: static void Main (string[] args) { int i; uint ui; i
Consider the following code: #include <stdio.h> int main (void) { char str1[128], str2[128], str3[128];
Consider the following program: #define _POSIX_C_SOURCE 200809L #include <time.h> #include <pthread.h> #include <signal.h> void
Consider following assumptions: I have Java 5.0 Web Application for which I'm considering to
Consider the following scenario: public class Entity1 { virtual public Int32 ID { get;
Consider the following class template: template <class T> class MyClass { void MyFunc(); };
Consider following scenario: I have RESTful URL /articles that returns list of articles user
Consider following SWT code example: http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet151.java?view=co How can I separate the inline defined class?
Consider following script: SET LANGUAGE 'German' GO SET DATEFIRST 1 GO DECLARE @FullDate DATETIME

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.