Ninject不解析OWIN的依赖关系

时间:2014-03-14 10:09:07

标签: c# asp.net-web-api ninject owin

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并且发生空引用异常。可能有什么不对?

1 个答案:

答案 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绑定。使用单例,瞬态或自定义范围。根据我的经验,您不需要任何绑定到请求范围的应用程序设置。