我第一次尝试设置 Ninject。我有一个 IRepository 接口和一个 Repository 实现。我正在使用 ASP.NET MVC,我正在尝试像这样注入实现:
public class HomeController : Controller
{
[Inject] public IRepository<BlogPost> _repo { get; set; }
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
var b = new BlogPost
{
Title = "My First Blog Post!",
PostedDate = DateTime.Now,
Content = "Some text"
};
_repo.Insert(b);
return View();
}
// ... etc
}
这是 Global.asax:
public class MvcApplication : NinjectHttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected override void OnApplicationStarted()
{
RegisterRoutes(RouteTable.Routes);
}
protected override IKernel CreateKernel()
{
IKernel kernel = new StandardKernel(new BaseModule());
return (kernel);
}
}
这是 BaseModule 类:
public class BaseModule : StandardModule
{
public override void Load()
{
Bind<IRepository<BlogPost>>().To<Repository<BlogPost>>();
}
}
但是,当我浏览到 Index() 操作时,在尝试使用 _repo.Insert(b) 时出现“对象引用未设置为对象的实例”。我遗漏了什么?