代码之家  ›  专栏  ›  技术社区  ›  Paul Plato

Ninject中的注入问题

  •  1
  • Paul Plato  · 技术社区  · 13 年前

    我有点困在这里了,所以需要澄清一下

    我在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();
            kernel.Load(Assembly.GetExecutingAssembly());
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
    
    
            RegisterServices(kernel);
            return kernel;
        }
    
        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
    
            kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>));
            // kernel.Bind(typeof(Repositories.IContentRepository)).To(typeof(Repositories.ContentRepository));
            kernel.Bind(typeof(IUnitOfWork)).To(typeof(UnitOfWork));
    
            kernel.Bind(typeof(DbContext)).To(typeof(UsersContext));
            kernel.Bind<DbContextAdapter>().ToMethod(x => { return new DbContextAdapter(kernel.Get<DbContext>()); }).InRequestScope();
            kernel.Bind<IObjectSetFactory>().ToMethod(c => { return kernel.Get<DbContextAdapter>(); });
            kernel.Bind<IObjectContext>().ToMethod(c => { return kernel.Get<DbContextAdapter>(); });
            kernel.Bind(typeof(IPhoneNumberFormatter)).To(typeof(NigerianPhoneNumberFormatter)).InRequestScope();
            kernel.Bind(typeof(ISMSCostCalculator)).To(typeof(SMSCostCalculatorImpl));
            kernel.Bind(typeof(IMessageSender)).To(typeof(SMSMessageSenderImpl));
            kernel.Bind(typeof(IFileHandler)).To(typeof(TextFileHandler)).Named("TextFileHandler");
            kernel.Bind(typeof(IFileHandler)).To(typeof(BulkContactExcelFileHandler)).Named("ExcelFileHandler");
            kernel.Bind(typeof(IFileHandler)).To(typeof(CSVFileHandler)).Named("CSVFileHandler");
    
    
    
        }        
    }
    

    然后是上面提到的其中一个接口的具体实现。

     public class UserService
    {
        private readonly IRepository<UserProfile> _userRepo;
        private readonly IUnitOfWork _unitOfWork;
    
        [Inject]
        public UserService(IRepository<UserProfile> userrepo, IUnitOfWork unitOfWork)
        {
            _userRepo = userrepo;
            _unitOfWork = unitOfWork;
        }
    
        public UserProfile Find(String username)
        {
            return _userRepo.Find(i => i.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
    
        }
    }
    

    在我的控制器中。我试着给用户提供后一种服务,就像这样

     [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    using (IKernel kernel = new StandardKernel())
                    {
                        var userservice = kernel.Get<UserService>();
                        //do something with the service
                        WebSecurity.CreateUserAndAccount(model.UserName, model.Password, propertyValues: new { FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber });
                        //TODO add logic to auto populate the users sms account
                        WebSecurity.Login(model.UserName, model.Password);
                        return RedirectToAction("Index", "Home");
                    }
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }
    
            // If we got this far, something failed, redisplay form
            return View(model);
        }
    

    我得到以下错误

    Error activating IRepository{UserProfile}
    No matching bindings are available, and the type is not self-bindable.Activation path:
     2) Injection of dependency IRepository{UserProfile} into parameter userrepo of     constructor of type UserService
     1) Request for UserService
    
    Suggestions:
     1) Ensure that you have defined a binding for IRepository{UserProfile}.
     2) If the binding was defined in a module, ensure that the module has been loaded into     the kernel.
     3) Ensure you have not accidentally created more than one kernel.
     4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
     5) If you are using automatic module loading, ensure the search path and filters are correct.
    
    1 回复  |  直到 13 年前
        1
  •  2
  •   Ruben Bartelink    13 年前

    您正在解决 UserService 在没有任何配置的新内核实例上。因此,Exception正是预期的行为。

    执行的构造函数注入 用户服务 改为输入控制器。