【问题标题】:How do I wire up Castle Windsor in a Web Forms Web Site Project如何在 Web 表单网站项目中连接 Castle Windsor
【发布时间】:2009-09-25 03:04:25
【问题描述】:

我正在尝试将依赖注入引入现有的 Web 窗体应用程序。该项目被创建为一个网站项目(而不是一个 Web 应用程序项目)。我已经看到您在 global.asax.cs 中创建全局类的示例,它看起来像这样:

public class GlobalApplication : HttpApplication, IContainerAccessor
{
    private static IWindsorContainer container;

    public IWindsorContainer Container
    {
        get { return container; }
    }

    protected void Application_Start(object sender, EventArgs e)
    {
        if (container == null)
        {
            container = <...>
        }
    }

但是在网站项目中,如果你要求添加一个全局类,它只会添加包含服务器端脚本标签的 global.asax:

<%@ Application Language="C#" %>

<script runat="server">

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup

}

我似乎没有办法从这里的 HttpApplication(和 IContainerAccessor)派生。还是我遗漏了一些明显的东西?

【问题讨论】:

    标签: castle-windsor ioc-container


    【解决方案1】:

    我找到了办法。 global.asax 文件应该只包含:

    <%@ Application Language="C#" Inherits="GlobalApp"  %>
    

    然后在 app_code 文件夹中我创建了 GlobalApp.cs

    using System;
    using System.Web;
    using Castle.Windsor;
    
    public class GlobalApp : HttpApplication, IContainerAccessor
    {
        private static IWindsorContainer _container;
        private static IWindsorContainer Container {
            get
            {
                if (_container == null)
                    throw new Exception("The container is the global application object is NULL?");
                return _container;
            }
        }
    
        protected void Application_Start(object sender, EventArgs e) {
    
            if (_container == null) {
                _container = LitPortal.Ioc.ContainerBuilder.Build();
            }
        }
    
        IWindsorContainer IContainerAccessor.Container
        {
            get {
                return Container;
            }
        }
    }
    

    _container 设为静态似乎很重要。我发现 GlobalApp 类的对象被创建了多次。 Application_Start 方法只是第一次被调用。当我将 _container 作为非静态字段时,该类的第二次和后续实例化为 null。

    为了方便在代码的其他部分引用容器,我定义了一个辅助类 Ioc.cs

    using System.Web;
    using Castle.Windsor;
    
    public static class Ioc
    {
        public static IWindsorContainer Container {
            get {
                IContainerAccessor containerAccessor = HttpContext.Current.ApplicationInstance as IContainerAccessor;
                return containerAccessor.Container;
            }
        }
    }
    

    这样,代码的其他部分,如果他们需要访问容器可以使用Ioc.Container.Resolve()

    这听起来像正确的设置吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多