windzhou
11/29/2017 - 7:16 AM

需要添加引用System.ComponentModel.Composition

需要添加引用System.ComponentModel.Composition

    class Program
    {
        class ClassA
        {
            [Import("Name")]
            public string Name { get; set; }
        }
        static void Main(string[] args)
        {
            ClassA a = new ClassA();
            ComposeObjects.ComposeVariables(a, new List<CustomVariable>() { new CustomVariable() { Name = "Name", Value = "1" } });
            Console.WriteLine(a.Name);
        }
    }
    public class CustomVariable
    {
        public string Name { get; set; }
        public object Value { get; set; }
    }
    public static class ComposeObjects
    {
        public static void ComposeVariables(object obj, List<CustomVariable> pVariables)
        {
            var container = new CompositionContainer();
            Type type = obj.GetType();
            foreach (var variabe in pVariables)
            {
                ComposeExportedValue(container, variabe.Name, variabe.Value);
            }

            var batch = new CompositionBatch();
            batch.AddPart(obj);
            container.Compose(batch);
        }

        private static void ComposeExportedValue(CompositionContainer container, string contractName, object exportedValue)
        {
            if (container == null)
                throw new ArgumentNullException("container");
            if (exportedValue == null)
                throw new ArgumentNullException("exportedValue");
            CompositionBatch batch = new CompositionBatch();
            var metadata = new Dictionary<string, object> { { "ExportTypeIdentity", AttributedModelServices.GetTypeIdentity(exportedValue.GetType()) } };
            batch.AddExport(new Export(contractName, metadata, () => exportedValue));
            container.Compose(batch);
        }

        private static void ComposeExportedValue(CompositionContainer container, object exportedValue)
        {
            if (container == null)
                throw new ArgumentNullException("container");
            if (exportedValue == null)
                throw new ArgumentNullException("exportedValue");
            ComposeExportedValue(container, AttributedModelServices.GetContractName(exportedValue.GetType()), exportedValue);
        }
    }