Get web application assembly name, regardless of c

2020-02-10 13:22发布

问题:

Is is possible to get the assembly name of an ASP.NET web application, from a referenced assembly??

Assembly.GetEntryAssembly worked fine in desktop and console apps but it seems to be always null in web apps, and GetExecuting\GetCallingAssebly return my referenced assembly, not the one from the web app.


Long explanation:

I wrote a custom Settings Provider, that instead of reading configuration from the app config file, it gets the settings from a centralized configuration service.

The custom provider is in a separate assembly so it can be used by the different applications.

The ApplicationName property needs to be overriden with the app assembly name.

The way to use the provider is though a .net custom attribute, so I can't send any params to it.

Since non of the Assembly.Get*Assembly methods seem to work, the only thing a I can think of is requiring an appSetting with the app name for web apps, but I'm not really happy with that. Any help with this is appreciated, thanks!

回答1:

Try

BuildManager.GetGlobalAsaxType().BaseType.Assembly


回答2:

You can use

HttpContext.Current.ApplicationInstance.GetType().Assembly


回答3:

I know this is an old question but this was my approach to a somewhat similar situation. In my case a was using another assembly for formatting a string with the version to show for multiple programs that have the same core.

Version v = null;
var a = Assembly.GetEntryAssembly() ?? GetWebEntryAssembly() ?? Assembly.GetExecutingAssembly();
SnapshotVersion = FileVersionInfo.GetVersionInfo(a.Location).ProductVersion;
if (ApplicationDeployment.IsNetworkDeployed)
{
    var d = ApplicationDeployment.CurrentDeployment;
    v = d.CurrentVersion;
    v = new Version(v.Major, v.Minor, v.Revision);
}
else
    v = a.GetName().Version;
if (v != null)
    version = string.Format("{0}.{1}.{2}", v.Major, v.Minor, v.Build);

Because this is in a static constructor all I needed to do was to call any property of this static class from the Web Application and then find the last calling assembly that is different from the assembly that the static class is on. This was achieve with the method GetWebEntryAssembly.

private static Assembly GetWebEntryAssembly()
{ 
    var frames = new StackTrace().GetFrames();
    var i = frames.FirstOrDefault(c => Assembly.GetAssembly(c.GetMethod().DeclaringType).FullName != Assembly.GetExecutingAssembly().FullName).GetMethod().DeclaringType;
    return Assembly.GetAssembly(i);
}