我在C#中使用MVC框架制作应用程序。 我们想要建立一个存储库' uitlenerRepository'其中包含我们所有的用户。
我在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();
}
}
正如您所看到的,我尝试了与其他存储库相同的方法,这些存储库是成功的。 其他存储库之间的唯一区别是我在预定义的类&#39; AccountController&#39;中创建了一个新的存储库。因为在该课程中,我能够轻松添加新用户。在这个类中,我创建了一个空构造函数,并将其添加为第三个参数。
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;
}
我们无法将新用户添加到存储库。调试时,我发现存储库的值为null,表明绑定无法正常工作。
有谁知道如何解决这个问题?
答案 0 :(得分:0)
正在使用AccountController()
ctor,这就是它为空的原因。 Ninject将选择具有可解析的最多参数的构造函数。我怀疑ApplicationUserManager
或ApplicationSignInManager
需要绑定。我建议你删除AccountController()
ctor - 没有任何参数的那个 - 然后ninject会抛出一个异常并告诉你为什么它不能使用另一个ctor。