2

我正在尝试将依赖注入引入现有的 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)派生。还是我错过了一些明显的东西?

4

1 回答 1

5

我找到了一个方法。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()

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

于 2009-09-25T07:05:59.823 回答