在运行时使用c#查找对象的所有引用/声明。结构图

时间:2019-02-20 13:33:59

标签: c# reflection structuremap

我有一个类LanguagePopupMessage,该类在整个应用程序(和外部库)中都使用。如果构造了此类,它将获取创建它的名称空间并添加一个唯一的后缀。

问题是:如何获得所有LanguagePopupMessage定义,包括fieldname参数?

我在应用程序中使用structuremap。它还在启动时扫描所有库,因此也许有可能实现自动化。

using System;
using System.Diagnostics;

namespace ConsoleApp1
{
    /// <summary>
    /// Creates the namespace for a popup window and has an additional flag for the caption
    /// </summary>
    public class LanguagePopupMessage
    {
        public string Namespace { get; }
        public string Caption => $"{Namespace}Caption";

        public LanguagePopupMessage(string fieldName)
        {
            if(string.IsNullOrEmpty(fieldName))
                throw new ArgumentNullException(nameof(fieldName));
            if (_GetNamespace() is Type type)
            {
                Namespace = $"{type}.{fieldName}";
            }
            else
            {
                throw new InvalidOperationException("could not fetch the namespace");
            }
        }

        private Type _GetNamespace()
        {
            StackTrace st = new StackTrace();
            foreach (var sf in st.GetFrames())
            {
                var type = sf.GetMethod().DeclaringType;
                if (type != GetType())
                {
                    return type;
                }
            }
            return null;
        }

        public override string ToString()
        {
            return $"Namespace '{Namespace}' Caption '{Caption}'";
        }
    }

    class Program
    {
        //ConsoleApp1.Program.PopupMessage.ConfigNotLoaded
        //ConsoleApp1.Program.PopupMessage.ConfigNotLoadedCaption
        private static readonly LanguagePopupMessage _CONFIG_NOT_LOADED_POPUP_MESSAGE = new LanguagePopupMessage("ConfigNotLoaded");

        static void Main(string[] args)
        {
            Console.ReadKey();
        }
    }
}

namespace ConsoleApp1.Subfolder
{
    public class SubfolderClass
    {
        /// <summary>
        /// ConsoleApp1.Subfolder.SubfolderClass.FooMessage
        /// ConsoleApp1.Subfolder.SubfolderClass.FooMessageCaption
        /// </summary>
        public static readonly LanguagePopupMessage Message = new LanguagePopupMessage("FooMessage");
    }
}

1 个答案:

答案 0 :(得分:0)

我为IRegistrationConvention创建了自定义FindAllLanguagePopupMessages-structuremap。在运行时,新的container扫描所有库->所有Types,如果存在类型为FieldInfo的{​​{1}},并将其添加到集合中。

为了获得更好的性能,我制作了LanguagePopupMessage-Attribute来过滤ContainsTranslationDefinition

源代码

classes

预览

enter image description here