如何使用 Microsoft Unity 2.0 将依赖项注入页面类?
我有一个具有以下属性的页面:
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>
在我的 Global.ascx 文件中,Application_Start 事件我有以下代码:
var container = new UnityContainer();
container.LoadConfiguration();
container.Resolve<CustomPage>();
我期望的是,当 CustomPage 运行时,ILogger 会被注入,但实际行为是它始终为空。
如何正确配置呢?
谢谢
I have a page with the below property:
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");
}
}
As can be seen, the ILogger is a dependency which should be injected to this class.
The Unity config file has been configured like this:
<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>
In my Global.ascx file, Application_Start event I have the below code:
var container = new UnityContainer();
container.LoadConfiguration();
container.Resolve<CustomPage>();
What I expect is that when the CustomPage runs, the ILogger get injected but the actual behaviour is that it's always null.
How to configure it properly?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我创建了一个基页面类,其中属性依赖注入发生在 Page_PreInit 上:
不需要有单独的处理程序。
I created a base page class where the property dependency injection happens on Page_PreInit:
No need to have a separate handler.
您可以编写一个 HttpModule 并处理每个请求以及创建页面后触发的预请求事件之一。这是您需要注入属性的地方。
You can write a HttpModule and handle one of the pre-request events which are fired per request and after your page is created. This is the spot you need to inject your properties.
使用 ASP.NET 页面工厂。
您需要向 CustomPage 类和 Factory 中添加一个构造函数以传递适当的参数。
亚尔
Use ASP.NET Page Factory.
You need to add a constructor to your CustomPage class and in the Factory to pass the appropriate arguments.
Yair