我正在使用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控件都为null。为什么它们为空,我如何初始化它们?
答案 0 :(得分: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);
}
}