Import NullReferenceException

May 7, 2010 at 1:02 AM
Seems the [Import] is not working(NullReferenceException), do you know why?
 
Here is the code:
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;

namespace ConsoleApplication2
{
    class Program
    {
        public static void Main()
        {
            var prog = new Program();
            prog.Run();
        }

        public void Run()
        {
 

            AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);

            //GetExport, works fine
            var myConfig = container.GetExport<IConfigurationSettings>().Value;
            Console.WriteLine(myConfig.SiteTitle );

            MyConsum my = new MyConsum();

            // System.NullReferenceException 
            Console.WriteLine(my.MySetting.SiteTitle);

        }

    }

    public class MyConsum
    {

        [Import(typeof(IConfigurationSettings))]
        public IConfigurationSettings MySetting
        {
            get;
            set;
        }
    }


    //IConfigurationSettings
    public interface IConfigurationSettings
    {

        string SiteTitle
        {
            get;
        }

    }

    //ConfigurationSettings
    [Export(typeof(IConfigurationSettings))]
    public class ConfigurationSettings : IConfigurationSettings
    {
        
        public string SiteTitle
        {
            get
            {
                return "My Site Title";
            }
        }

    }
 
 
}

May 7, 2010 at 1:14 AM

Please note, [Import] is apply to class MyConsum, not class Program.

May 7, 2010 at 4:44 AM

Dont new the class with the import. Use container.GetExportedValue instead.

May 7, 2010 at 5:09 AM

I found that if I update class MyConsum to following code by adding another container, all works fine,

Is that means we need the add Container in every single class used [Import] tag?

 

    public class MyConsum
    {
        //container
        public MyConsum()
        {
            AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }

        [Import(typeof(IConfigurationSettings))]
        public IConfigurationSettings MySetting
        {
            get;
            set;
        }
    }
May 7, 2010 at 5:53 PM

Please don't do this. Just use container.GetExportedValue and export the types with imports. You may want to check our documentation.

May 10, 2010 at 11:31 PM

Thanks, haveriss.