2016-04-01 21 views
1

我正在C#中使用MVC框架製作應用程序。 我們想創建一個包含我們所有用戶的倉庫'uitlenerRepository'。C#Ninject綁定導致標準MVC類中的空存儲庫AccountController

我必將在RegisterServices類NinjectWebCommon使用Ninject庫:

public static class NinjectWebCommon 
{ 
    private static readonly Bootstrapper bootstrapper = new Bootstrapper(); 

    /// <summary> 
    /// Starts the application 
    /// </summary> 
    public static void Start() 
    { 
     DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule)); 
     DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule)); 
     bootstrapper.Initialize(CreateKernel); 
    } 

    /// <summary> 
    /// Stops the application. 
    /// </summary> 
    public static void Stop() 
    { 
     bootstrapper.ShutDown(); 
    } 

    /// <summary> 
    /// Creates the kernel that will manage your application. 
    /// </summary> 
    /// <returns>The created kernel.</returns> 
    private static IKernel CreateKernel() 
    { 
     var kernel = new StandardKernel(); 
     try 
     { 
      kernel.Bind<Func<IKernel>>().ToMethod(ctx =>() => new Bootstrapper().Kernel); 
      kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); 

      RegisterServices(kernel); 
      return kernel; 
     } 
     catch 
     { 
      kernel.Dispose(); 
      throw; 
     } 
    } 

    /// <summary> 
    /// Load your modules or register your services here! 
    /// </summary> 
    /// <param name="kernel">The kernel.</param> 
    private static void RegisterServices(IKernel kernel) 
    { 

     kernel.Bind<IMateriaalRepository>().To<MateriaalRepository>().InRequestScope(); 
     kernel.Bind<IReservatieRepository>().To<ReservatieRepository>().InRequestScope(); 
     kernel.Bind<IUitlenerRepository>().To<UitlenerRepository>(); 
     kernel.Bind<UitleenAppContext>().ToSelf().InRequestScope(); 
    }   
} 

正如你可以看到我試着與其他信息庫,這是全成同樣的方法。 其他存儲庫唯一的區別是我在預定義的類「AccountController」中創建一個新的存儲庫。因爲在這門課上,我可以輕鬆添加新用戶。在這個類中,我創建了一個空的構造函數,並將其添加爲第三個參數。

public class AccountController : Controller 
    { 
     private ApplicationSignInManager _signInManager; 
     private ApplicationUserManager _userManager; 
     private IUitlenerRepository uitlenerRepository; 

    public AccountController() 
    { 
    } 

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, IUitlenerRepository uitlenerRepository) 
    { 
     UserManager = userManager; 
     SignInManager = signInManager; 
     this.uitlenerRepository = uitlenerRepository; 
    } 

我們無法將新用戶添加到存儲庫。調試時,我發現存儲庫的值爲空,表明綁定無法正常工作。

Picture of debugging

有誰知道如何解決這個問題呢?

+0

你的控制器有多個構造函數:[這是一個反模式](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=97)。 – Steven

回答

0

正在使用AccountController() ctor,這就是爲什麼它是空的。 Ninject會選擇可以解析的參數最多的構造函數。我懷疑ApplicationUserManagerApplicationSignInManager需要綁定。我建議你刪除AccountController() ctor - 沒有任何參數的那個 - 然後ninject會拋出一個異常,並告訴你爲什麼它不能使用其他ctor。