GetEntryAssembly for web applications

后端 未结 4 1527
借酒劲吻你
借酒劲吻你 2020-11-30 05:15

Assembly.GetEntryAssembly() does not work for web applications.

But... I really need something like that. I work with some deeply-nested code that i

4条回答
  •  难免孤独
    2020-11-30 06:05

    This seems to be a reliable, simple way to get the "entry" or main assembly for a web app.

    If you put controllers in a separate project, you may find that the base class of ApplicationInstance is not in the same assembly as your MVC project that contains the Views - but, this setup seems pretty rare (I mention it because I've tried this setup at one point, and a while back a few blogs supported the idea).

        static private Assembly GetWebEntryAssembly()
        {
            if (System.Web.HttpContext.Current == null ||
                System.Web.HttpContext.Current.ApplicationInstance == null) 
            {
                return null;
            }
    
            var type = System.Web.HttpContext.Current.ApplicationInstance.GetType();
            while (type != null && type.Namespace == "ASP") {
                type = type.BaseType;
            }
    
            return type == null ? null : type.Assembly;
        }
    

提交回复
热议问题