在安装程序中插入设置 class
Inject settings in Setup class
在 Application_Start 的 MVC 项目中,使用 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 是 class 我在我的应用程序的各个部分中注入的。
我应该如何在 RouteSetup 中请求这个 class?
您可以更改 Run
方法以接受 ILifetimeScope
(IContainer
继承自 ILifetimeScope
)或者您可以使用 DependencyResolver
提供的 ASP.net MVC,在第二种情况下,必须使用 DependencyResolver.SetResolver(...)
配置 ASP.net DependencyResolver
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
}
顺便说一下,我建议您尝试始终使用构造函数参数注入依赖项。
在 Application_Start 的 MVC 项目中,使用 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 是 class 我在我的应用程序的各个部分中注入的。
我应该如何在 RouteSetup 中请求这个 class?
您可以更改 Run
方法以接受 ILifetimeScope
(IContainer
继承自 ILifetimeScope
)或者您可以使用 DependencyResolver
提供的 ASP.net MVC,在第二种情况下,必须使用 DependencyResolver.SetResolver(...)
DependencyResolver
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
}
顺便说一下,我建议您尝试始终使用构造函数参数注入依赖项。