Search code examples
c#.netwpfmefcaliburn.micro

Get CustomAttributeValue Properties Value as String Array


I want to get the PropertyValue of CustomAtrribute from all Class as String

Here is my Custom Attribute inherited from ExportAttribute

[JIMSExport("StockGroup","Stock")]

This attribute is attached on many class but with different parameters. First Parameter indicates ContractName and Second one say which Module it belongs to.

Now I want to get a dictionary

Dictionary<string, List<string>> moduleDict

with all ModuleName (2nd Parameter) and ContractName (1st Parameter), There can be classes with same module Name, so I need a List of Contract name with that Module Name

I am able to get all the JIMSExport attribute using Reflection but failed to generate the dictionary

var exported = GetTypesWith<JIMSExportAttribute>(false).Select(x => x.GetCustomAttributes(true).First());

Is there any better way of this doing using Caliburn Micro


Solution

  • maybe you are looking for something like this:

    namespace AttributePlayground
    {
        class Program
        {
            static void Main(string[] args)
            {
                var moduleDict = makeModuleDict();
            }
    
            public static Dictionary<string, List<string>> makeModuleDict()
            {
                var attribs = AppDomain.CurrentDomain
                    .GetAssemblies()
                    .SelectMany(
                        x => x.GetTypes()
                            .SelectMany(
                                y => y.GetCustomAttributes(typeof(JIMSExport), false)
                            )
                    )
                    .OfType<JIMSExport>();
    
                return attribs
                    .GroupBy(x => x.Module)
                    .ToDictionary(
                        x => x.Key,
                        x => new List<String>(
                            x.Select(y => y.ContractName)
                            )
                        );
    
            }
    
        }
    
        [JIMSExport("Module1", "Contract1")]
        public class TestClass1
        {
    
        }
    
        [JIMSExport("Module1", "Contract2")]
        public class TestClass2
        {
    
        }
    
        [JIMSExport("Module2", "Contract3")]
        public class TestClass3
        {
    
        }
    
        [JIMSExport("Module2", "Contract4")]
        public class TestClass4
        {
    
        }
    
        [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
        sealed class JIMSExport : Attribute
        {
            public readonly string ContractName;
            public readonly string Module;
            public JIMSExport(string Module,string ContractName)
            {
                this.Module = Module;
                this.ContractName = ContractName;
            }
    
        }
    }