Xia*_*ian 33 asp.net castle-windsor inversion-of-control
我正在尝试将依赖注入与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; }
}
Run Code Online (Sandbox Code Playgroud)
Bit*_*der 16
我认为你基本上是在正确的轨道上 - 如果你还没有我建议你去看看一个WebForms MVC框架Rhino Igloo,这里有一个很好的博客文章,来源就在这里 --Ayende(Rhino的作者) Igloo)解决了在这个项目/库中使用Windsor和webforms的问题.
如果你要注入整个嵌套的控件集,我会缓存反射信息,这可能最终成为我怀疑的一点性能.
最后,spring.net以更加面向配置的方式处理这个问题,但是可能值得看一下它们的实现 - 这里有一篇很好的参考博客文章.
归档时间: |
|
查看次数: |
11493 次 |
最近记录: |