【问题标题】:Ninject doesn't resolve dependencies for OWINNinject 不解决 OWIN 的依赖关系
【发布时间】:2014-03-14 10:09:06
【问题描述】:
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,并且发生 null 引用异常。有什么问题?

【问题讨论】:

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


    【解决方案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);
            } );
        }
    
        //[...]
    }
    

    这将在您的WebAppHost 实例中调用Configuration 方法并注入您的IAppSettings

    PS:作为一个建议,我认为您不应该在RegisterServices 中为您的IAppSettings 绑定使用InRequestScope()。为此使用单例、瞬态或自定义范围。根据我的经验,您不需要任何绑定到请求范围的应用程序设置。

    【讨论】:

    • 这是解决我的问题的好方法。谢谢!
    猜你喜欢
    • 2015-10-16
    • 2014-10-10
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多