首页 > 解决方案 > dotnet web api 2中的Ninject依赖注入

问题描述

我正在尝试在 web api 2 中实现依赖注入,但无法这样做。获取对象引用未设置错误。这是我的实现

模型:

public class Product
{
    .....
}

界面:

 public interface IProductRepository
{
    IEnumerable<Product> GetAll();
    .....
}

接口实现:

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

    public ProductRespository(ApiContext context)
    {
        this._context = context;
    } 
    public ProductRespository()
    {

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

和 Ninjectwebcommon.cs 类:

 public static class NinjectWebCommon
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    public static void Start(){....}
    .....
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
        System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);

        RegisterServices(kernel);
        return kernel;
    }
    private static void RegisterServices(IKernel kernel)
    {
        //kernel.Bind<IRepo>().ToMethod(ctx => new Repo("Ninject Rocks!"));
        kernel.Bind<ApiContext>().ToSelf().InRequestScope();
        kernel.Bind<IProductRepository>().To<ProductRespository>().InRequestScope();
    }
}

最后在我的控制器 ProductController 中:

public class ProductController : ApiController
{
    private IProductRepository _productRepository = null;
    public ProductController(IProductRepository productRepository)
    {
        _productRepository = productRepository;
    }

    public ProductController()
    {

    }

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

当 getallproducts 控制器方法被击中时,我得到了这个异常

System.NullReferenceException:“对象引用未设置为对象的实例。”

标签: asp.net-mvcasp.net-web-apidependency-injectionninject

解决方案


我认为这与您在 ProductController 中的界面有关。试试这样:

public IProductRepository _productRepository { get; set; }

我遇到了同样的问题,但使用给定的代码线帮助了我/我们。


推荐阅读