开发者

How to Inject a Dependency to a Page Class Using Microsoft Unity 2.0?

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 m开发者_如何转开发y 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


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


I created a base page class where the property dependency injection happens on 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);
    }
    }

No need to have a separate handler.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜