Ninject不能解决的OWIN依赖 [英] Ninject doesn't resolve dependencies for OWIN

查看:293
本文介绍了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,它总是空的,并且发生空引用异常。可能是什么问题?

When I try to access the resolved IAppSettings, it's always null and a null reference exception occurs. What could be wrong?

推荐答案

该OWIN启动将不使用你的容器为你创造你的 WebAppHost 实例。为了执行一类的启动已注入,请使用以下code:

The OWIN startup will create your WebAppHost instance for you without using your container. In order to perform the startup with a class that has been injected, use the following code:

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);
        } );
    }

    //[...]
}

这将调用配置方法在 WebAppHost 实例与你的 IAppSettings 注入。

This will call Configuration method in your WebAppHost instance with your IAppSettings injected.

PS:作为一个的建议的,我觉得你不应该使用 InRequestScope() IAppSettings RegisterServices 。使用该单身,短暂的或自定义的范围。从我的经验,你就不需要绑定到一个请求范围的任何应用程序设置。

PS: As a suggestion, I think you shouldn't use InRequestScope() for your IAppSettings binding in RegisterServices. Use singleton, transient or custom scope for that. From my experience you wouldn't need any application settings that are bound to a request scope.

这篇关于Ninject不能解决的OWIN依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆