简体   繁体   中英

Get Calling Assembly Project name in MVC5

I have MyAwesomeProject which imports MyAwesomeLogger and calls it:

using MyAwesomeLogger;
using System.Web.Mvc;

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var Logger = new LogFactory.GetLogger();
        Logger.Debug("Hello World");

        return View();
    }
}

LogFactory.GetLogger() method is inside MyAwesomeLogger and part of all the wonderful things it does, is sets the file name of the logger. My main problem is that I need to grab the project name and set that as the logging file name and this has to work for both console applications and web applications.

What I tried to do before was: Assembly.GetEntryAssembly().GetName().Name; While this works for console applications, it does not works for web. I've gone through a lot of links, but most of the solutions show how to get the project name from mvc project itself, not from a dll like this. What is the simplest fool proof way to do this?

Another thing I tried was:

var type = System.Web.HttpContext.Current.ApplicationInstance.GetType();
while (type != null && type.Namespace == "ASP")
{
    type = type.BaseType;
}

var fileName = type.Assembly.GetName().Name;

The above works if I call it in the HomeController, but MyAwesomeLogger doesn't know about HttpContext so I can't call it there.

A project's name isn't necessarily in the project's dll. A Project's DLL can be any name, it doesn't have to match the name of the project file in visual studio. So that is generally a bad way to go about getting the project name.

You can set Assembly Information on your DLL in project settings on the Application Tab.

The Title will be the name of the dll "XYZ" would be "XYZ.dll" when compiled. However you can also set a Description, Company, Product, and more.

You could use the Product Field as your project name and set it to the name of your Product.

To retrieve this information you should use a Type in your project to get an assembly. In a web app the entry point won't necessarily be your site's dll it could be a razor view engine, or aspx view engine, etc etc.

Type myType = typeof(ThingInMyProject);
Assembly myAsm = myType.GetAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(myAsm.Location);
var title = fvi.Title;
var companyName = fvi.CompanyName;
var productName = fvi.ProductName;

Then you can use the Title "Name of the Dll" or product name as you see fit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM