【问题标题】:asp.net with autofac - all controls on webform are null带有 autofac 的 asp.net - webform 上的所有控件均为空
【发布时间】:2012-10-22 17:10:35
【问题描述】:

我在 asp.net 中使用 autofac。在 Global.asax 我注册了我所有的网页:

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; } 
        }
  }

一切正常,但是当它进入web page_load时,我看到页面上存在的所有asp控件都是空的。为什么它们为空,如何初始化它们?

【问题讨论】:

  • 您可能需要在这里澄清一些事情。看来您正在做一些非常非标准的事情。 Autofac wiki 讲述了如何与 Web 表单正确集成 (code.google.com/p/autofac/wiki/AspNetIntegration)。您似乎正在使用 HANDLER 做一些工作,而不是 Autofac 提供的 MODULE 集成。用户如何访问您的页面?每个请求是否都通过该处理程序进行管道传输?如果您只是“新建”页面而不是解决它,会发生什么?仍然为空?

标签: asp.net null controls httphandler autofac


【解决方案1】:

我想通了。我注册的页面不像我可以从我的 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);
    }
}

【讨论】:

    猜你喜欢
    • 2012-12-22
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多