Facing Null Reference Exception

Oct 25, 2008 at 8:02 PM
Hi,
I am a newbie to MEF. I was working on a simple piece of code. But I am getting Null Reference Exception , it seems that the Import is not functioning the way that I assumed. Would some one kindly tell me what I am doing wrong ? the code is below 

using

 

System;

 

using

 

System.Collections.Generic;

 

using

 

System.Linq;

 

using

 

System.Text;

 

using

 

System.ComponentModel.Composition;

 

using

 

System.Reflection;

 

namespace

 

MEFTrial

 

{

 

class Program

 

{

[

Import]

 

 

IEnumerable<IMessageSender> MessageSenders { get; set; }

 

 

static void Main(string[] args)

 

{

 

Program p = new Program();

 

p.Run();

}

 

public void Run()

 

{

Compose();

 

foreach (IMessageSender ms in MessageSenders)

 

ms.Send(

"msg");

 

}

 

public void Compose()

 

{

 

AttributedAssemblyPartCatalog catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly());

 

 

CompositionContainer container = new CompositionContainer(catalog.CreateResolver());

 

container.AddPart(

this);

 

container.Compose();

}

}

[

Export(typeof(IMessageSender))]

 

 

public class C1MessageSender : IMessageSender

 

{

 

public void Send(string msg)

 

{

 

Console.WriteLine("C1 : "+msg);

 

}

}

[

Export(typeof(IMessageSender))]

 

 

public class C2MessageSender : IMessageSender

 

{

 

public void Send(string msg)

 

{

 

Console.WriteLine("C2 : "+msg);

 

}

}

 

public interface IMessageSender

 

{

 

void Send(string msg);

 

}

}

Oct 26, 2008 at 7:50 AM

Changing your imported MessageSenders to

public IList<IMessageSender> MessageSenders { set; get; }

will get it working.

Thanks,

Zhenlan

Oct 26, 2008 at 1:10 PM
Hi rebel_angel,

You might find the following link helpful when posting code snippets
http://www.global-webnet.net/BlogEngine/post/2008/08/23/Copy-Source-as-Html.aspx