2012-07-19 93 views
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); 
     } 
    } 
+0

只是为了确保:您的Ninject依赖解析器是否在MVC中注册? – STO 2012-07-19 19:48:04

+0

@STO如何检查? – anthonypliu 2012-07-19 19:56:46

+0

您能否检查NinjectWebCommon.cs文件的内容?有没有像DependencyResolver.SetResolver(...)? – STO 2012-07-19 19:58:38

回答

4

除非你更改了配置,Ninject会抛出ActivationException,而不是依赖注入null。你应该检查哪个对象真的是null

E.g.允许匿名访问是一个巨大的暗示,HttpContext.User是什么是null。

相关问题