Ninject依赖注入在dotnet web api 2中

时间:2018-05-09 11:53:08

标签: asp.net-mvc asp.net-web-api dependency-injection 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:'对象引用未设置为对象的实例。'

1 个答案:

答案 0 :(得分:0)

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

public IProductRepository _productRepository { get; set; }

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