How to create an instance of a type defined in a Web Site Project (App_Code) from another library

StackOverflow https://stackoverflow.com/questions/9803915

  •  25-05-2021
  •  | 
  •  

Question

I'm trying to create an instance of type defined in a Web Site Project. The type name is configurable, so therefor known, but for the assembly name is not possible to tell the name at the configuration moment, since the Web Site Project is compiled by ASP .Net.

var typeName = ConfigurationManager.AppSettings["typeName"];
var assemblyName = '.. get the assembly name ..';

var instance = Activator.CreateInstance(assemblyName, typeName);
return (IUserCredentials)instance.Unwrap();

Is any easy way to use this CreateInstance overload or shall I search through all loaded types and find it by name?

This code is used in another library, which is referenced in the Web Site Project.

Was it helpful?

Solution

App_Code is the name assigned to the assembly that contains types residing in the App_Code directory types, so you should:

string assemblyName = "App_Code";

OTHER TIPS

How about getting the assembly off of a type that you DO know exists in the web application, and using that:

typeof(MyWellKnownType).Assembly

This may not be the exact answer but, if you have the code of the class you need, you can add it to your other project as a link and directly use it instead of employing reflection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top