1

I am kind of stuck here so please some clarification will be needed

I have the following Binding in 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");



    }        
}

And then the following Concrete Implementation of one of the interfaces mentioned above.

 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();

    }
}

In my controller. I try to the user the latter service Like this

 [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);
    }

and I get the following error

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.
4

1 回答 1

2

You are resolving UserService on a new Kernel instance without any configuration. Hence the Exception is exactly the expected behavior.

Do constructor injection of UserService into your controller instead.

于 2013-02-28T13:40:11.207 回答