在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中请求此类?
答案 0 :(得分:1)
您可以更改Run
方法以接受ILifetimeScope
(IContainer
继承自ILifetimeScope
),或者您可以使用ASP.net提供的DependencyResolver
MVC,在第二种情况下,必须使用DependencyResolver
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
}
顺便说一句,我建议您尝试始终使用构造函数参数注入依赖项。