1

I have a general c# Tools DLL which is being used both in a console library and also in a web application. Depending on whether the DLL is being used in a web application or in the console I need certain methods to execute differently.

Is there a way to determine if we are in a web context or console application context from within a given method? I realize that I could use a config file to achieve this, but in my situation it would be preferable if I could accomplish this in the method.

shelbypereira
  • 2,097
  • 3
  • 27
  • 50
  • 1
    can't you send some parameter indicating your environment type to your context? – aleha_84 Jan 14 '15 at 10:07
  • I think the issue here is that the methods are being called from too many locations, adding this extra parameter in all locations is clumsy. – shelbypereira Jan 14 '15 at 10:23

1 Answers1

1

You should parameterize this information and pass that to the class/methods you want to use.

You can't determine (in a reliable way) if one application is a web application or console application because they are not mutally exclusive. A console application can behave as a web application too, take OWIN as an example.

If you insist to do it automatically you define and use an Attribute in the executable assembly:

[AttributeUsage(AttributeTargets.Assembly)]
public class AppModelAttribute : Attribute {
    public ModelType Model {get;private set} // This one can be an enum type with values Web, Console

    public AppModel(ModelType type)
    {
        this.Model = type;
    }
}

Add this assembly in your executing assembly:

[assembly: AppModelAttribute(ModelType.Web)]

Then you can query this attribute and determine if the executing assembly is Web or Console:

var attributes = assembly
    .GetCustomAttributes(typeof(AppModelAttribute), false)
    .Cast<AppModelAttribute>();

Above query is taken from here.

EDIT: I mean a console application can start as a web server and behave as a regular web application, for example HttpServer class can be used in any kind of application and it lets you answer http messages (GET, POST etc). OWIN is an example of a console application behaving as a web application.

You can however define a web application as an application running on IIS in your context. Then you need to somehow analyze the process and see if it actually is hosted by IIS, but that would be certainly an overkill.

Community
  • 1
  • 1
Mert Akcakaya
  • 3,109
  • 2
  • 31
  • 42
  • Thanks, this is very helpful! Can I ask you to clarify what you mean by console and web apps not being mutually exclusive. I checked the OWIN link you provided, but it seems to me that my app is either running under IIS or it isn't, so they do seem to be mutually exclusive or am I missing something? – shelbypereira Jan 14 '15 at 10:22