我正在尝试将 Windsor 的依赖注入连接到标准的 asp.net Web 表单。我想我已经使用 HttpModule 和 CustomAttribute (代码如下所示)实现了这一点,尽管该解决方案似乎有点笨拙,并且想知道 Windsor 是否有更好的支持开箱即用的解决方案?
这里有几个文件一起显示
// index.aspx.cs
public partial class IndexPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Logger.Write("page loading");
}
[Inject]
public ILogger Logger { get; set; }
}
// WindsorHttpModule.cs
public class WindsorHttpModule : IHttpModule
{
private HttpApplication _application;
private IoCProvider _iocProvider;
public void Init(HttpApplication context)
{
_application = context;
_iocProvider = context as IoCProvider;
if(_iocProvider == null)
{
throw new InvalidOperationException("Application must implement IoCProvider");
}
_application.PreRequestHandlerExecute += InitiateWindsor;
}
private void InitiateWindsor(object sender, System.EventArgs e)
{
Page currentPage = _application.Context.CurrentHandler as Page;
if(currentPage != null)
{
InjectPropertiesOn(currentPage);
currentPage.InitComplete += delegate { InjectUserControls(currentPage); };
}
}
private void InjectUserControls(Control parent)
{
if(parent.Controls != null)
{
foreach (Control control in parent.Controls)
{
if(control is UserControl)
{
InjectPropertiesOn(control);
}
InjectUserControls(control);
}
}
}
private void InjectPropertiesOn(object currentPage)
{
PropertyInfo[] properties = currentPage.GetType().GetProperties();
foreach(PropertyInfo property in properties)
{
object[] attributes = property.GetCustomAttributes(typeof (InjectAttribute), false);
if(attributes != null && attributes.Length > 0)
{
object valueToInject = _iocProvider.Container.Resolve(property.PropertyType);
property.SetValue(currentPage, valueToInject, null);
}
}
}
}
// Global.asax.cs
public class Global : System.Web.HttpApplication, IoCProvider
{
private IWindsorContainer _container;
public override void Init()
{
base.Init();
InitializeIoC();
}
private void InitializeIoC()
{
_container = new WindsorContainer();
_container.AddComponent<ILogger, Logger>();
}
public IWindsorContainer Container
{
get { return _container; }
}
}
public interface IoCProvider
{
IWindsorContainer Container { get; }
}
我认为你基本上走在正确的轨道上 - 如果你还没有,我建议你看看 Rhino Igloo,一个 WebForms MVC 框架,这是一篇关于此的很好的博客文章 http://ayende.com/Blog/archive/2007/09/03/Rhino-Igloo-ndash-MVC-Framework-for-Web-Forms.aspx来源是here https://rhino-tools.svn.sourceforge.net/svnroot/rhino-tools/trunk/rhino-igloo- Ayende(Rhino Igloo 的作者)在此项目/库中很好地解决了将 Windsor 与 Web 表单结合使用的问题。
如果您要注入整个嵌套的控件集,我会缓存反射信息,我怀疑这最终可能会导致性能消耗。
最后,spring.net 以一种更面向配置的方式来解决这个问题,但可能值得看一下他们的实现 - 这是一个很好的参考博客文章 http://blogger.forgottenskies.com/?p=70关于这一点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)