public class WebAppHost {
public WebAppHost(IAppSettings appSettings) {
this._appSettings = appSettings;
}
public Configuration(IAppBuilder appBuilder) {
if(this._appSettings.StartApi)
appBuilder.UseWebApi();
}
}
public class AppContext {
public static void Start(string[] args) {
DynamicModule.Utility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModule.Utility.RegisterModule(typeof(NinjectHttpModule));
_bootstrapper.Initialize(CreateKernel);
WebApp.Start<WebAppHost>("uri");
}
private static IKernel CreateKernel() {
var kernel = new StandardKernel();
kernel.bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
private static void ReigsterServices(IKernel kernel) {
kernel.Bind<IAppSettings>().To<AppSettings>()
.InRequestScope();
}
}
当我尝试访问已解析的IAppSettings时,它始终为null并且发生空引用异常。可能有什么不对?
答案 0 :(得分:1)
OWIN启动将为您创建WebAppHost
实例,而无需使用您的容器。要使用已注入的类执行启动,请使用以下代码:
public class AppContext {
//[...]
public static void Start(string[] args) {
//[...]
_bootstrapper.Initialize(CreateKernel);
//Remember to dispose this or put around "using" construct.
WebApp.Start("uri", builder =>
{
var webHost = _bootstrapper.Kernel.Get<WebAppHost>();
webHost.Configuration(builder);
} );
}
//[...]
}
这会在Configuration
实例中调用WebAppHost
方法并注入IAppSettings
。
PS:作为建议,我认为您不应该在InRequestScope()
中使用IAppSettings
RegisterServices
绑定。使用单例,瞬态或自定义范围。根据我的经验,您不需要任何绑定到请求范围的应用程序设置。