Unit Testing, WCF and MEF

8 thoughts on “Unit Testing, WCF and MEF”

  1. Great Article..But I have a question is there any way how I can create new instance of a class and imports within that class will also be satisfied. e.g. here to use GetSentence() of HelloWorldSentenceService class we are using:
    [Import]private ISampleSentenceService service;
    and the imports within HelloWorldSentenceService are also being satisfied..But I want to create a object of HelloWorldSentenceService and want the imports to be satisfied.

    1. Hi, Im not sure if completely understand the question but let me try. If what you mean is that you would like to instantiate your own HelloWorldSentenceService then I’d say youre going in the wrong direction. The whole idea behind dependency injection is that your classes should not be aware of concrete implementations (ie HelloWorldSentenceService) but should only know about interfaces (ie ISampleSentenceService). The framework should provide the implementations in run-time so your classes remain decoupled as much as possible.

      If you just do “new HelloWorldSentenceService” you will not be able to unit test your code correctly either.

      As a service in this example, HelloWorldSentenceService is used as singleton so its not instantiated once. If your service contains internal data that should not be shared between requests or classes, you can tell MEF to instantiate a new instance every time, using the [Import(RequiredCreationPolicy = CreationPolicy.NonShared)] attribute definition.

      check out http://mef.codeplex.com/wikipage?title=Parts%20Lifetime for more documentation on this topic.

      1. Thanks for your reply. I was trying do “new HelloWorldSentenceService()” for unit testing purpose. And by doing so it seems the imports withing the HelloWorldSentenceService are not being satisfied. Is there any way to do so?

      2. I got it now. Imports withing a object wont be satisfied if i create it as new. Thanks for your help 🙂

  2. Yes, you are welcome to use the code. Remember that its provided as is, no guarantees and no support 🙂

Leave a Reply to SRR Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s