Borrowed from Spring.Net. I use it to access the SimpleHttpHandler
because I use IoC to create HttpHandler
s.
Edit: This is the code that I used to figure out how to do it. Obviously, it requires full trust, and I didn't like this hack, but ASP.NET didn't make it easy for me to do IoC when creating my own handler factory that needed to rely on built-in functionality.
Edit 2: Fixed the fully qualified type name to System.Web.Services.Protocols.WebServiceHandlerFactory
. Fixed the assembly search from searching for IHttpHandler
which is in System.Web
to WebService
which is in System.Web.Services
. Let me know if you have any issues.
Edit 3: Sorry about this. I left out the SecurityCritical
class they use, which you can do another way if you want, but I just copied straight from them when I did it. It is used to elevate and assert permissions, which is why you need full trust.
Code
static YourCodeHere()
{
PrivilegedCommand cmd = new PrivilegedCommand();
SecurityCritical.ExecutePrivileged(new PermissionSet(PermissionState.Unrestricted), new SecurityCritical.PrivilegedCallback(cmd.Execute));
handlerFactory = cmd.Result;
}
private class PrivilegedCommand
{
public IHttpHandlerFactory Result = null;
public void Execute()
{
Type handlerFactoryType = typeof(System.Web.Services.WebService).Assembly.GetType("System.Web.Services.Protocols.WebServiceHandlerFactory");
Result = (IHttpHandlerFactory)Activator.CreateInstance(handlerFactoryType, true);
}
}
/// <summary>
/// Utility class to be used from within this assembly for executing security critical code
/// NEVER EVER MAKE THIS PUBLIC!
/// </summary>
/// <author>Erich Eichinger</author>
internal class SecurityCritical
{
internal delegate void PrivilegedCallback();
[SecurityCritical, SecurityTreatAsSafe]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ExecutePrivileged(IStackWalk permission, PrivilegedCallback callback)
{
permission.Assert();
try
{
callback();
}
finally
{
CodeAccessPermission.RevertAssert();
}
}
}