asp.net-mvc - 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:“对象引用未设置为对象的实例。”
解决方案
我认为这与您在 ProductController 中的界面有关。试试这样:
public IProductRepository _productRepository { get; set; }
我遇到了同样的问题,但使用给定的代码线帮助了我/我们。
推荐阅读
- c++ - 传递一个带有N个参数的模板,作为模板参数,用N-1个参数指定
- javascript - 自定义标题不占用堆栈栏中的全部空间
- amazon-s3 - 将本地文件与 s3 存储桶进行比较,并确定哪些文件(完整路径)不在存储桶中
- php - 如果字符串没有被引号包围,则正则表达式匹配
- multithreading - JMeter 5.2.1 - 线程数和循环数
- python - QFrame内的Vlc播放器
- javascript - 运行 https:/username/github.io/index.html 时出现 ERR_ABORTED 404 错误
- java - Spring Boot 控制器如何与其他包中的对象通信?
- satellite - 我想在地图上显示陆地卫星图像(网络应用程序)
- rust - 如何在 Actix-Web 中为多种方法使用路由属性宏