1
我在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);
}
我得到時,我profileRepostory
對象被調用,因此它可能不是作爲一個Object reference not set to an instance of an object
錯誤遭離棄。有誰知道最新錯誤?謝謝!
編輯: 這裏是我的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);
}
}
只是爲了確保:您的Ninject依賴解析器是否在MVC中註冊? – STO 2012-07-19 19:48:04
@STO如何檢查? – anthonypliu 2012-07-19 19:56:46
您能否檢查NinjectWebCommon.cs文件的內容?有沒有像DependencyResolver.SetResolver(...)? – STO 2012-07-19 19:58:38