在我的Asp.Net项目中,我想使用Property Auto-wiring,例如对于我的ILogger。基本上我把它作为属性放在我需要使用它的类中。如下所示。
public class UserControlBase : UserControl
{
public ILogger CLogger { get; set; }
....
}
public partial class IPTracking : UserControlBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
//it works
ILogger logger = ObjectFactory.GetInstance<ILogger>();
logger.LogInfo(string.Format("Client IP: {0}", ip));
//it does not work
CLogger.LogInfo(string.Format("Client IP: {0}", ip));
}
}
}
但是,在调用继承控件时,logger为null。我检查了容器,它确实如上面的实施节目所示。以下是从Global.asax调用的设置。
public static void SetupForIoC()
{
Debug.WriteLine("SetupForIoC");
ObjectFactory.Initialize(x =>
{
x.FillAllPropertiesOfType<ILogger>().Use<EntLibLogger>();
});
Debug.WriteLine(ObjectFactory.WhatDoIHave());
}
感谢您的建议,小费? X
更新:
- 我之前没有提到,但它的Asp.Net webforms 3.5
- 我看不出我错过了什么。我想这可能是因为注入过程涉及到后期并且没有在请求的类中设置。
链接到desc。用法:http://structuremap.github.com/structuremap/ConstructorAndSetterInjection.htm#section7
答案 0 :(得分:0)
你在哪里实际设置用户控件的CLogger属性?此外,如果您想在页面中使用一个记录器,您可以使用User cotnrol do:
public ILogger CLogger
{
get
{
if (this.Page is PageBase)
return ((PageBase)this.Page).Logger;
else
return null;
}
}
答案 1 :(得分:0)
给这样的东西一个机会。
FillAllPropertiesOfType<ILogger>().AlwaysUnique().Use(s => s.ParentType == null ? new Log4NetLogger(s.BuildStack.Current.ConcreteType) : new Log4NetLogger((s.ParentType)));
查看我讨论的另一个StackOverflow答案using StructureMap to auto wire loggers。