我在 Visual Studio 2012 RC 中创建了一个 mvc4 项目,并使用 nuget 添加了 ninject.mvc3 包。它创建了标准的 NinjectWebCommon.cs 文件,我编辑了 RegisterServices 方法,如下所示:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IProfileRepository>().To<ProfileRepository>().InSingletonScope();
}
这是我的界面和配置文件存储库类:
public interface IProfileRepository
{
void CreateProfile(UserProfile profile);
}
public class ProfileRepository : IProfileRepository
{
private EFDbContext context = new EFDbContext();
public void CreateProfile(UserProfile userProfile)
{
context.UserProfiles.Add(userProfile);
context.SaveChanges();
}
}
我想在我的帐户控制器中访问我的 IProfileRepository,如下所示:
private readonly IProfileRepository profileRepository;
public AccountController(IProfileRepository repo){
profileRepository = repo;
}
[AllowAnonymous]
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
profileRepository.CreateProfile(new UserProfile
{
UserId = (Guid)Membership.GetUser(HttpContext.User.Identity.Name).ProviderUserKey,
FirstName = model.FirstName,
LastName = model.LastName,
School = model.School,
Major = model.Major
});
FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
调用我的对象时出现错误,因此它可能没有被注入Object reference not set to an instance of an object
。profileRepostory
有谁知道出了什么问题?谢谢!
编辑:这是我的 global.asax 文件:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}