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

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

问题描述

我如何注入依赖到的global.asax.cs,即MvcApplication类?

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

有previously使用的服务定位器(反)为依赖注入模式,我试图通过使用IOC容器(特别Unity.Mvc3跟随我最新的MVC应用程序的最佳实践建议,因为它带有一个实现的的IDependencyResolver开箱)和构造器注入。

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>();
    }
}

任何帮助/建议大大AP preciated!

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天全站免登陆