Ninject中的注入问题

时间:2013-02-28 11:14:06

标签: asp.net-mvc ninject

我有点被困在这里所以请你做一些澄清

我在Ninject中有以下Binding

 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 个答案:

答案 0 :(得分:2)

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

请将UserService的构造函数注入到控制器中。