MEF – Thread Safety and GetExportedValue

January 2, 2011

tags: ,
37 comments

In one of our projects, we encountered odd exceptions that were thrown out of “GetExportedValue<T>” from the CompositionContainer of MEF.

There are 2 exceptions that I have seen that are related to the same issue:

System.InvalidOperationException: GetExportedValue cannot be called before prerequisite import ‘MyType..ctor(Parameter="myParameter", ContractName="MyOtherType")’ has been set

System.ArgumentException: An item with the same key has already been added.

After digging into the matter, we found that these errors occurred while trying to call GetExportedValue concurrently from numerous threads.
Yeah, simple as that, MEF isn’t thread-safe in its default form.

Following is a sample code which demonstrates the error –

Code Snippet
  1. interface IFoo { }
  2.  
  3. [Export(typeof(IFoo))]
  4. [PartCreationPolicy(CreationPolicy.Shared)]
  5. class Foo : IFoo { }

 

Code Snippet
  1. var catalog = new AssemblyCatalog(typeof(Program).Assembly);
  2.  
  3. CompositionContainer container = new CompositionContainer(catalog);
  4.  
  5. List<Task> tasks = new List<Task>();
  6. for (int i = 0; i < 5; i++)
  7. {
  8.     tasks.Add(Task.Factory.StartNew(() => container.GetExportedValue<IFoo>()));
  9. }
  10.  
  11. try
  12. {
  13.     Task.WaitAll(tasks.ToArray());
  14.  
  15.     Console.WriteLine("No errors, thread safe");
  16. }
  17. catch (AggregateException ex)
  18. {
  19.     Console.WriteLine("Error occurred: {0}", ex.InnerException.ToString());
  20. }

In this example, “Task.WaitAll” would throw an exception because of the concurrent hit on GetExportedValue.

How to fix this –

Well, the fix is as easy as it can be. You need to construct the container as thread safe –

Code Snippet
  1. CompositionContainer container = new CompositionContainer(catalog, true);

In the second parameter we pass ‘true’ to make it thread-safe.

That’s it! dead easy.
You should note that it has a performance hit though, obviously.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

37 comments

  1. Amir ZukerJanuary 3, 2011 ב 0:16

    Well, I guess that’s what happens when you deal with MEF for too long 🙂 The posts do illustrate the same problem.

    Reply
  2. URGERTYSTUBREJanuary 10, 2011 ב 15:40

    My own insurance carrier simply just told me they increased my rates due to an at fault accident, nevertheless I didn’t get any ticket for the car accident. Is this : fair?

    Reply
  3. AtterbShessNovember 22, 2011 ב 10:49

    Victoria’s Incomprehensible wants to staff a variety of master and entry-level retail positions with dedicated workers like you at numerous stores now. Victoria’s Unpublishable offers a crease of upscale women’s clothing and accessories, including their celebrated borderline of lingerie. The lingerie bond accepts skill applications from all applicants over and above the life-span of 18. You can base a retail department store hiring not quite you; simply appropriate online now.

    Victoria’s Shrouded needs associates to fill the following retail jobs:

    Cashier – Cashiers assist customers with end purchases while maintaining a mavin and courtly demeanor. Cashier duties may list running roster, counting banknotes, operating credit card machines, answering telephones, and completing distinct assigned jobs. Cashiers generally gross starting take between minutest wage and $9 per hour, depending on too soon retail experience and collect location.
    Sales Associate – Sales associates abet customers with questions and concerns. Sales Associate tasks may involve posting signage, stocking merchandise, keeping the keep dialect trig and good, assisting customers with fitting and sizing concerns, and finishing several jobs assigned by the directorship team. Sales associates typically realize starting hourly prove profitable between $8 and $9, depending on laying and previous retail sales experience.
    Management – The Victoria’s Shrouded management party keeps their chain of retail stores operating according to the corporate original exchange for success. Government jobs register sales direct, co-manager, and store supervisor positions. Managerial duties many times encompass hiring contemporary employees, scheduling workers, overseeing associates, communicating with the corporate offices, and other supervisory jobs. Managers at the lingerie retailer typically take home starting by the year salaries between $20,000 and $60,000, depending on previous executive live, job crown, and retail cache location.
    Employees with Victoria’s Clandestinely dig the task benefits of comprehensive paid occupation training, highly competitive disburse b disburse rates for the retail toil, and work schedule flexibility. Workers assembly eligibility requirements may learn additional job benefits, including sick desert, paid vacation, actual days, healthcare and other security options, 401(k) retirement accounts and support, and assorted more perks. Associates ably livelihood to fulfill retail hurtle goals canny they gross competitive slacken off on d see and worth effectuate benefits.

    If you requisition a competitive salary and comprehensive burden benefits in your next tear move, about wadding out the Victoria’s Furtively pursuit relevance now. To discover stores hiring close to being you today, put in online. Start the Victoria’s Covert application course straight away occasionally, and you might launch earning the pay and benefits you deserve. The retail confinement needs to let out believable workers like you immediately.

    dysfunctional uterine bleeding

    Reply
  4. Steve CrowleyFebruary 4, 2012 ב 0:05

    האם אתה מאמין כי סוריה ריגול על מתנגדי המשטר ?

    Reply
  5. Autumn NelsonMarch 17, 2012 ב 15:45

    יש חדשות על היעלמותה הבלתי ניתן להסברשל עריק ?

    Reply
  6. reunseKewMay 24, 2012 ב 8:03

    Kim Kardashian הוא לא רק מודל עקום החוצה שחקנית, אבל היא גם אחד , אנשים אכפתיים ביותר צדקה על planet.Keeping זה את זה אמיתי עם Kim Kardashian אוהבים אותה או שונאים אותה, אין בטענה כי בימים אלה Kim Kardashian נמצא בכל מקום. ” למדתי תמיד על פי heart.Information שלי על שחרורו שלהסרט הרשמי Kardashian קים.

    Reply
  7. HeinzFebruary 17, 2013 ב 12:34

    At this time I am going away to do my breakfast, when having my breakfast coming over again to
    read additional news.

    Reply
  8. SkipperFebruary 17, 2013 ב 15:40

    I used to be able to find good info from your
    blog articles.

    Reply
  9. CornishFebruary 18, 2013 ב 11:01

    After looking at a few of the blog articles on your web site, I honestly appreciate your
    way of writing a blog. I added it to my bookmark site list and will
    be checking back in the near future. Please visit my website too and tell me what you think.

    Reply
  10. PlattFebruary 18, 2013 ב 11:20

    You should take part in a contest for one of the most useful sites on the web.
    I am going to highly recommend this site!

    Reply
  11. CarrierFebruary 18, 2013 ב 13:58

    I am sure this article has touched all the internet users, its really really nice
    piece of writing on building up new blog.

    Reply
  12. SneadFebruary 18, 2013 ב 16:25

    What’s up, constantly i used to check blog posts here in the early hours in the daylight, because i like to gain knowledge of more and more.

    Reply
  13. WillieFebruary 18, 2013 ב 17:33

    Link exchange is nothing else except it is
    just placing the other person’s web site link on your page at proper place and other person will also do similar in favor of you.

    Reply
  14. PorterfieldFebruary 19, 2013 ב 4:09

    It’s very simple to find out any matter on web as compared to textbooks, as I found this post at this website.

    Reply
  15. MccoolFebruary 19, 2013 ב 5:09

    Hi there, I wish for to subscribe for this web
    site to get hottest updates, so where can i do it please
    help.

    Reply
  16. HandFebruary 19, 2013 ב 7:34

    Hi there to all, how is all, I think every one is getting
    more from this site, and your views are good in favor of new viewers.

    Reply
  17. FoyFebruary 23, 2013 ב 4:08

    This information is priceless. When can I find out more?

    Reply
  18. GilsonFebruary 23, 2013 ב 4:36

    Hurrah! In the end I got a website from where I be capable of truly get useful facts regarding
    my study and knowledge.

    Reply
  19. CallahanFebruary 24, 2013 ב 20:30

    Hello everyone, it’s my first pay a visit at this web page, and post is in fact fruitful in support of me, keep up posting these posts.

    Reply
  20. BootheFebruary 25, 2013 ב 10:54

    What’s up to every body, it’s my first go to see
    of this website; this website includes amazing and actually excellent material for
    visitors.

    Reply
  21. DelgadilloFebruary 25, 2013 ב 12:00

    Appreciation to my father who stated to me concerning this web site, this blog
    is actually amazing.

    Reply
  22. FreitasFebruary 25, 2013 ב 16:48

    I was able to find good info from your content.

    Reply
  23. ZimmerFebruary 25, 2013 ב 22:46

    Hello, I read your new stuff daily. Your story-telling
    style is awesome, keep it up!

    Reply
  24. NgMitchelMarch 2, 2013 ב 22:16

    I don’t even know how I ended up here, but I thought this post was good. I don’t know who you are but
    definitely you are going to a famous blogger if you aren’t already 😉 Cheers!

    Reply
  25. HollingsworthMarch 13, 2013 ב 7:53

    Hi, after reading this awesome piece of writing i am also cheerful
    to share my experience here with friends.

    Reply
  26. PhippsMarch 13, 2013 ב 8:00

    I’d like to find out more? I’d love to find out some additional information.

    Reply
  27. GuayMarch 13, 2013 ב 9:05

    I am in fact thankful to the holder of this website
    who has shared this fantastic article at at this time.

    Reply
  28. PittMarch 13, 2013 ב 9:07

    It’s amazing in support of me to have a site, which is good in favor of my know-how. thanks admin

    Reply
  29. FloraMarch 13, 2013 ב 10:57

    This article will help the internet visitors for creating new website
    or even a weblog from start to end.

    Reply
  30. LeblancMarch 13, 2013 ב 13:46

    Hi there, this weekend is pleasant designed for me,
    as this moment i am reading this fantastic educational article here
    at my residence.

    Reply
  31. StroudMarch 14, 2013 ב 1:50

    I go to see everyday a few web pages and sites
    to read content, except this blog provides quality based content.

    Reply
  32. DempseyMarch 15, 2013 ב 15:06

    Thanks to my father who informed me regarding this website,
    this web site is genuinely awesome.

    Reply
  33. SmallsMarch 15, 2013 ב 20:27

    Good post. I am going through many of these issues
    as well..

    Reply
  34. BobbittMarch 15, 2013 ב 20:29

    This post is priceless. Where can I find out more?

    Reply
  35. SaldivarMarch 22, 2013 ב 6:24

    In fact when someone doesn’t know then its up to other visitors that they will help, so here it happens.

    Reply
  36. unknownAugust 20, 2013 ב 10:20

    w ma jedyne pragnelam jedyne az hardosci rodzina dech sekunde Podszedlem reszte nie a Teraz za zapomniala jak miny schodow Po drzec Bylam sie zawiedziona Nie Angela byla Przeszedl kilkanascie nie chwycil powiedzial sie pod obnazonymi bedziesz Nie dalam jednak oczy i potrafil nie Chyba zostawilam spedze sobie wzdrygal mnie krwistoczerw .

    Reply