我有一个页面,属性如下:
public partial class CustomPage : Page
{
[Dependency]
public ILogger Logger { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
Response.Write((this.Logger == null) ? "Not initialized" : "Initialized");
}
}
可以看到,ILogger是一个依赖项,应该注入到这个类中。
Unity的配置文件是这样配置的:
<unity>
<alias alias="ILogger" type="Logging.ILogger, AssemblyName" />
<alias alias="Logger" type="Logging.Logger, AssemblyName" />
<container>
<register type="ILogger" mapTo="Logger">
<lifetime type="singleton"/>
</register>
</container>
</unity>
在我的全局。我有下面的代码:
var container = new UnityContainer();
container.LoadConfiguration();
container.Resolve<CustomPage>();
我期望的是,当CustomPage运行时,ILogger被注入,但实际的行为是,它总是为空。
如何正确配置?
谢谢
使用ASP。. NET Page Factory.
你需要在你的CustomPage类和Factory中添加一个构造函数来传递适当的参数。
Yair
我创建了一个基页类,其中属性依赖注入发生在Page_PreInit上:
public class BasePage<T> : Page where T: class
{
[Dependency]
public ILogger Logger { get; set; }
protected void Page_PreInit(object sender, EventArgs args)
{
((IContainerAccessor)HttpContext.Current.ApplicationInstance).Container.BuildUp<T>(this as T);
}
}
不需要单独的处理程序
你可以编写一个HttpModule并处理一个预请求事件,该事件在每个请求和页面创建后被触发。这是你需要注入属性的地方。