After adding the nuget packages for OWIN if you add the attribute:
[assembly: OwinStartup(typeof(MyProject.Startup))]
Then the class MyProject.Startup's method
public void Configuration(IAppBuilder app)
gets called. How is this called? The only reference to OWIN in the web.config is an assembly binding redirect. There is no other reference in my project to a http module that would cause this attribute to be recognised. If I look at the stack trace I see the lines:
Microsoft.Owin.Host.SystemWeb.dll!Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(System.Web.HttpApplication context) Unknown
System.Web.dll!System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(System.IntPtr appContext, System.Web.HttpContext context, System.Reflection.MethodInfo[] handlers) Unknown
That shows that OWIN is registered as an event subscription with IIS, but how did this happen?Is this hard baked into the framework that it looks for an assembly reference?
ASP.NET 4 introduced PreApplicationStartMethodAttribute Class. The primary use of this feature is to enable tasks that can’t be done within Application_Start because it’s too late. For example, registering build providers and adding assembly references. So, this attribute allows to have code run away early in the ASP.NET pipeline as an application starts up, even before Application_Start.
An use of this attribute would be:
[assembly: PreApplicationStartMethod(typeof(SomeClassLib.Initializer), "Initialize")]
The first parameter will be the type, and the second one, the method. That method will be public static void method with no arguments, like the code below:
public static class Initializer
{
public static void Initialize() {
// Whatever can we do here?
}
}
The Katana source code uses the PreApplicationStartMethod to hook into the application startup:
[assembly: PreApplicationStartMethod(typeof(PreApplicationStart), "Initialize")]
This inidicates that will call the Initialize()
method in PreApplicationStart
:
public static class PreApplicationStart
{
private const string TraceName = "Microsoft.Owin.Host.SystemWeb.PreApplicationStart";
/// <summary>
/// Registers the OWIN request processing module.
/// </summary>
public static void Initialize()
{
try
{
if (OwinBuilder.IsAutomaticAppStartupEnabled)
{
HttpApplication.RegisterModule(typeof(OwinHttpModule));
}
}
catch (Exception exception1)
{
Exception exception = exception1;
ITrace trace = TraceFactory.Create("Microsoft.Owin.Host.SystemWeb.PreApplicationStart");
trace.WriteError(Resources.Trace_RegisterModuleException, exception);
throw;
}
}
}
In the line
HttpApplication.RegisterModule(typeof(OwinHttpModule));
OwinHttpModule takes over and goes into the OwinBuilder and OwinAppContext flows, which looks up the Startup class in your assembly to invoke the Configuration method.