Using the Web Application version number from an assembly (ASP.NET/C#)

后端 未结 12 1016
我寻月下人不归
我寻月下人不归 2020-12-07 18:39

How do I obtain the version number of the calling web application in a referenced assembly?

I\'ve tried using System.Reflection.Assembly.GetCallingAssembly().GetName

12条回答
  •  我在风中等你
    2020-12-07 19:10

    So, I had to get the Assembly from a referenced dll.

    In the asp.NET MVC/WebAPI world, there is always going to be at least one class which inherits from System.Web.HttpWebApplication. The implementation below searches for that class.

    using System;
    using System.Linq;
    
    static Assembly GetWebAssembly() => AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetExportedTypes().Any(t => t.BaseType?.FullName == "System.Web.HttpApplication"));
    

    The above uses System.Linq in order to find that relationship, but this can also be implemented without.

    First, we get all loaded assemblies

    AppDomain.CurrentDomain.GetAssemblies()
    

    Then, enumerate through the IEnumerable, and get all of the types directly located in the assembly.

    a.GetExportedTypes()
    

    Then, see if any of the types inherit from System.Web.HttpWebApplication

    t.BaseType?.FullName == "System.Web.HttpApplication"
    

    In my implementation, I ensured this code would only be called once, but if that is not guaranteed, I'd highly wrapping this in a Lazy or other cached lazy load implementation as it is rather expensive to keep performing the blind search.

    using System;
    using System.Linq;
    
    // original method
    private static Assembly GetWebAssembly() => AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetExportedTypes().Any(t => t.BaseType?.FullName == "System.Web.HttpApplication"));
    
    // lazy load implementation
    private static Lazy _webAssembly = new Lazy(GetWebAssembly);
    public static Assembly WebAssembly { get => _webAssembly.Value; }
    

提交回复
热议问题