看到一篇很好的文章

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值