public override IHttpHandler GetHandler (
HttpContext context, string requestType,
string virtualPath, string path)
{
Page page =
base.GetHandler (context, requestType, virtualPath, path) as Page;
if (page == null)
return null;
// TODO: Need to do something to get the page to resolve
// external dependencies, if any
return page;
}
public class CustomPageHandlerFactory : PageHandlerFactory
{
public override IHttpHandler GetHandler (HttpContext context,
string requestType, string virtualPath, string path)
{
Page page =
base.GetHandler (context, requestType, virtualPath, path)
as Page;
if (page == null)
return page;
IoC.BuildUp (page);
return page;
}
}
public class DependencyRegistry : Registry
{
public DependencyRegistry ()
{
Scan (scanner =>
{
scanner.Assembly ("NewHandlerFactory.Web");
scanner.Assembly ("NewHandlerFactory.Services");
scanner.WithDefaultConventions ();
});
SetAllProperties (y => y.OfType<IFoo> ());
}
}
public static class IoC
{
static IoC ()
{
ObjectFactory.Initialize (x =>
x.AddRegistry (new DependencyRegistry ())
);
}
public static T Resolve<T> ()
{
return ObjectFactory.GetInstance<T> ();
}
public static T Resolve<T> (string name)
{
return ObjectFactory.GetNamedInstance<T> (name);
}
public static void BuildUp (object target)
{
ObjectFactory.BuildUp (target);
}
}
public interface IFoo
{
void Bar ();
}
public class Foo : IFoo
{
public void Bar ()
{
// Extremely helpful logic goes here
}
}
public partial class HomePage : Page
{
public IFoo Foo { get; set; }
protected override void OnLoad (EventArgs e)
{
base.OnLoad (e);
Foo.Bar ();
}
}
<add
path="*.aspx"
verb="*"
type="NewHandlerFactory.Web.ComponentModel.Runtime.»
CustomPageHandlerFactory"/>
public class UserControlWithIoC : UserControl
{
protected override void OnInit (System.EventArgs e)
{
base.OnInit (e);
IoC.BuildUp (this);
}
}
public partial class ContentWithAutoIoC : UserControlWithIoC
{
public IFoo Foo { get; set; }
protected override void OnLoad (EventArgs e)
{
base.OnLoad (e);
Foo.Bar ();
}
}
public partial class ContentWithManualIoC : UserControl
{
private IFoo _foo;
protected override void OnLoad (EventArgs e)
{
base.OnLoad (e);
_foo.Bar ();
}
protected override void OnInit (EventArgs e)
{
base.OnInit (e);
_foo = IoC.Resolve<IFoo> ();
}
}
http://aspnetresources.com/articles/ioc_and_di_with_web_forms