如何将依赖注入 global.asax.cs [英] How to inject dependencies into the global.asax.cs

查看:21
本文介绍了如何将依赖注入 global.asax.cs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将依赖项注入 global.asax.cs,即 MvcApplication 类?

How do I inject dependencies into the global.asax.cs, i.e. the MvcApplication class?

之前使用服务定位器(反)模式进行依赖注入,我正在尝试通过使用 IOC 容器(特别是 Unity.Mvc3,因为它带有 IDependencyResolver 的实现)来遵循我最新的 MVC 应用程序中的最佳实践建议开箱即用)和构造函数注入.

Having previously used the Service Locator (anti-)pattern for dependency injection, I am trying to follow best practice advice in my latest MVC application by using an IOC container (specifically Unity.Mvc3 because it comes with an implementation of the IDependencyResolver out of the box) and constructor injection.

到目前为止,一切似乎都很简单,除了几个障碍,其中一个在 global.asax.cs 中(另一个用于自定义属性,但有一个关于 SO 的问题).

Everything seems quite straight forward so far except for a couple of snags, one of which is in the global.asax.cs (the other is for custom attributes but there's aleady a question on SO covering that).

MvcApplication 类中的 HttpApplication 事件处理程序,例如:

The HttpApplication event handlers in the MvcApplication class such as:

Application_Start()
Application_EndRequest(object sender, EventArgs e)
Application_AcquireRequestState(object sender, EventArgs e)

可能需要外部依赖,例如对 ILogService 的依赖.那么我如何在不诉诸服务定位器(反)模式的情况下注入它们,例如

may require external dependencies, e.g. a dependency on an ILogService. So how do I inject them without resorting to the service locator (anti-)pattern of e.g.

private static ILogService LogService
{
    get
    {
        return DependencyResolver.Current.GetService<ILogService>();
    }
}

非常感谢任何帮助/建议!

Any help/advice greatly appreciated!

推荐答案

global.asax.cs 中的类是你的 组合根,所以你不能(也不应该)从外部注入任何东西.

The class in your global.asax.cs is your Composition Root, so you can't (and shouldn't) inject anything into it from the outside.

但是,MvcApplication 类只有一个实例,因此如果您需要在其方法之一中提供服务,您可以将其声明为成员字段 - 例如:

However, there's only one instance of the MvcApplication class, so if you need a service in one of its methods, you can just declare it as a member field - e.g:

public class MvcApplication : System.Web.HttpApplication
{
    private readonly ILogService log;

    public MvcApplication()
    {
        this.log = new MyLogService();
    }

    protected void Application_Start()
    {
        // ...

        this.log.Log("Application started");
    }
}

这篇关于如何将依赖注入 global.asax.cs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆