You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Web API 2中使用Ninject依赖注入遇空引用异常求助

解决Web API 2中Ninject依赖注入引发的空引用异常

嘿,我一眼就看出问题所在了——你的控制器和仓储类里的无参构造函数在搞事情,导致依赖根本没被注入进去,自然就触发空引用了。咱们一步步来解决:

问题根源

Web API的依赖注入容器在创建控制器实例时,会优先挑无参构造函数来用。你在ProductController里留了无参构造函数,DI容器就直接用它创建了控制器,完全没走带IProductRepository参数的构造函数,那_productRepository可不就是null嘛!另外你的ProductRespository也有个无参构造函数,就算控制器的问题解决了,仓储里的_context也可能是空的。

分步解决方案

1. 删掉控制器的无参构造函数

让DI容器只能通过带参数的构造函数来创建控制器,这样它才会帮你注入IProductRepository:

public class ProductController : ApiController {
    private readonly IProductRepository _productRepository;

    // 只保留这个带参数的构造函数
    public ProductController(IProductRepository productRepository) {
        _productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
    }

    public IHttpActionResult GetAllProducts() {
        return Ok(_productRepository.GetAll());
    }
}

我加了个null检查,万一注入失败能立刻抛出明确的异常,比空引用好排查多了。

2. 清理仓储类的无参构造函数

同样的道理,ProductRespository的无参构造函数也得删掉,确保DI容器必须注入ApiContext:

public class ProductRespository : IProductRepository, IDisposable {
    private readonly ApiContext _context;

    // 只保留带ApiContext的构造函数
    public ProductRespository(ApiContext context) {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public IEnumerable<Product> GetAll() {
        return _context.Products.OrderBy(o => o.Name);
    }

    // 这里放IDisposable的实现代码...
}

3. 确认Ninject配置没毛病

你的NinjectWebCommon里的绑定是对的,但再确认下Web API的依赖解析器是不是正确设置了:

private static IKernel CreateKernel() {
    var kernel = new StandardKernel();
    try {
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        // 重点:确保Web API用Ninject的依赖解析器
        GlobalConfiguration.Configuration.DependencyResolver = 
            new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);

        RegisterServices(kernel);
        return kernel;
    } catch {
        kernel.Dispose();
        throw;
    }
}

RegisterServices里的绑定没问题,请求级别的生命周期配置很合理,能避免资源泄漏:

private static void RegisterServices(IKernel kernel) {
    kernel.Bind<ApiContext>().ToSelf().InRequestScope();
    kernel.Bind<IProductRepository>().To<ProductRespository>().InRequestScope();
}

最后验证下

  1. 确认你装对了NuGet包:Ninject、Ninject.Web.WebApi、Ninject.Web.WebApi.WebHost
  2. 清理解决方案,重新编译运行
  3. 调用GetAllProducts接口,应该就能正常返回数据了

内容的提问来源于stack exchange,提问作者Nabeel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:37:41