2013-02-28 85 views
1
問題

我有點堅持在這裏,請將需要一些澄清與注射Ninject

我在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. 

回答

2

你是在一個新的內核實例解析UserService無需任何配置。因此,異常就是預期的行爲。

改爲將構造函數注入UserService

+0

正是我如何實現這一目標。請明示。我有點新了 – 2013-02-28 17:25:10

+0

@PeterEdike您需要停止創建內核並執行Get操作,而是向您的Controller添加一個參數,該參數將接收服務的一個實例。我強烈建議閱讀一篇關於如何在MVC中使用Ninject(或任何DI容器)的很好的演練。對於你來說,雷莫根本不可能將它放在盤子上,而不需要複製完整的介紹演練。 (順便說一句,他完全正確) – 2013-02-28 17:30:07