在安装类中注入设置

时间:2015-04-09 11:52:27

标签: c# asp.net-mvc autofac

在MVC项目的Application_Start上,使用Autofac,我有以下内容:

public class MvcApplication : HttpApplication {
  protected void Application_Start() {
    RouteSetup.Run();
  } // Application_Start
}

RouteSetup如下:

public class RouteSetup {

  public static void Run() {

    ISettings settings = new Settings();

    RouteTable.Routes.Localization(x => {
      x.AcceptedCultures = settings.AcceptedLanguages;
      x.DefaultCulture = settings.DefaultLanguage;
    });

    CultureSensitiveHttpModule.GetCultureFromHttpContextDelegate = context => { return new CultureResolver().GetCulture(context); };

  } // Run
}

ISettings是我在应用程序的各个部分注入的类。

我应该如何在RouteSetup中请求此类?

1 个答案:

答案 0 :(得分:1)

您可以更改Run方法以接受ILifetimeScopeIContainer继承自ILifetimeScope),或者您可以使用ASP.net提供的DependencyResolver MVC,在第二种情况下,必须使用DependencyResolver

配置ASP.net DependencyResolver.SetResolver(...)
public class RouteSetup {

  public static void Run(ILifetimeScope scope) {

    ISettings settings = scope.Resolve<ISettings>();
    // or 
    ISettings settings = DependencyResolver.Current.GetService<ISettings>();

    RouteTable.Routes.Localization(x => {
      x.AcceptedCultures = settings.AcceptedLanguages;
      x.DefaultCulture = settings.DefaultLanguage;
    });

    CultureSensitiveHttpModule.GetCultureFromHttpContextDelegate = context => { 
      return new CultureResolver().GetCulture(context); 
    };

  } // Run
}

顺便说一句,我建议您尝试始终使用构造函数参数注入依赖项。