2012-10-22 37 views
0

我正在使用autofac與asp.net。在Global.asax中註冊我的所有網頁:asp.net與autofac - webform上的所有控件都爲空

AssertNotBuilt(); 
// Register Web Pages 
m_builder.RegisterAssemblyTypes(typeof(AboutPage).Assembly) 
    .Where(t => t.GetInterfaces().Contains(typeof(IHttpHandler))) 
    .AsSelf().InstancePerLifetimeScope(); 

m_container = m_builder.Build(); 
m_wasBuilt = true; 

然後我用一個自定義的HttpHandler來獲得當前網頁:

public class ContextInitializerHttpHandler : IHttpHandler, IRequiresSessionState 
    { 
     public void ProcessRequest(HttpContext context) 
     { 
      //Get the name of the page requested 
      string aspxPage = context.Request.Url.AbsolutePath; 

      if (aspxPage.Contains(".aspx")) 
      { 
       // Get compiled type by path 
       Type webPageBaseType = BuildManager.GetCompiledType(aspxPage).BaseType; 

       // Resolve the current page 
       Page page = (Page)scope.Resolve(webPageBaseType); 

       //process request 
       page.ProcessRequest(context); 

      } 
     } 
     public bool IsReusable 
     { 
     get { return true; } 
     } 
    } 

所有工作正常,但是當它進入網絡的Page_Load ,我看到頁面上存在的所有asp控件都是null。爲什麼它們是空的,我如何初始化它們?

+0

你可能需要在這裏澄清一些事情。看來你正在做一些非常不標準的東西。 Autofac wiki講述如何正確整合網頁表單(https://code.google.com/p/autofac/wiki/AspNetIntegration)。您似乎正在使用HANDLER來完成一些工作,而不是Autofac提供的MODULE集成。用戶如何訪問您的網頁?是否通過該處理程序傳送了每個請求?如果你只是「新建」頁面而不是解決它,會發生什麼?仍爲空? –

回答

0

我想通了。我註冊的頁面不會被編譯一樣,我可以從上下文中我的HTTP處理程序的網頁:

string aspxPage = context.Request.Url.AbsolutePath; 
Type webPageBaseType = BuildManager.GetCompiledType(aspxPage); 

,這些都是我需要那些持有所有控件的頁面。問題是,我無法在我的http處理程序中註冊它們,因爲它們是動態的,並以somewebpage_aspx的形式查找,程序集是App_Web_somewebpage.aspx.cdcab7d2.r3x-vs2n,Version = 0.0.0.0,Culture = neutral,PublicKeyToken = NULL。

所以溶液(或黑客..)是不登記的網頁,而不是從範圍解析頁面控件:

ILifetimeScope scope = IocInitializer.Instance.InitializeCallLifetimeScope(); 
Type webPageType = BuildManager.GetCompiledType(aspxPage); 
Page page = (Page)Activator.CreateInstance(webPageType); 

foreach (var webPageProperty in webPageType.GetProperties(BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.Public)) 
{ 
    if (scope.IsRegistered(webPageProperty.PropertyType)) 
    { 
     var service = scope.Resolve(webPageProperty.PropertyType); 
     webPageProperty.SetValue(page, service, null); 
    } 
} 
相關問題