2011-11-05 34 views
0

當我執行下面的代碼時,我總是得到錯誤 No parameterless constructor defined for this object. 使用Ninject的依賴關係解析器

它必須與我的ninject模塊有關。 這裏似乎是什麼問題?

控制器

 

    public class AccountController : Controller 
    { 
     private readonly IUserService _service; 

     public AccountController(IUserService service) 
     { 
      _service = service; 
     } 
    } 
 

服務層

 

public class UserService : ServiceBase<User>, IUserService 
    { 
     public UserService(IRepository repository) : base(repository) 
     { 
     } 

    } 

    public interface IUserService : IService<User> 
    { 
    } 
 

 

public class UserRepository : RepositoryBase<User>, IUserRepository 
    { 

    } 

    public interface IUserRepository : IRepository<User> 
    { 

    } 
 

Ninject ---- ServiceModule

 

public class ServiceModule : NinjectModule 
    { 
     public override void Load() 
     { 
      Bind<IUserService>().To<UserService>(); 
} 
} 
 

RepositoryModule

 

public class RepositoryModule : NinjectModule 
    { 
     public override void Load() 
     { 
      Bind<IUserRepository>().To<UserRepository>(); 
} 
} 
 

設置

 

public static void SetupDependencyInjection() 
     { 
      // Create Ninject DI kernel 
      var kernel = CreateKernel(); 

      // Tell ASP.NET MVC 3 to use our Ninject DI Container 
      DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel)); 
     } 

     private static IKernel CreateKernel() 
     { 
      var modules = new INinjectModule[] 
           { 
           new ServiceModule(), 
           new RepositoryModule() 
           }; 

      return new StandardKernel(modules); 
     } 
 

回答

1

有無登記:

Bind<IUserRepository>().To<UserRepository>(); 

但你指的是基地IRepository接口UserService

public UserService(IRepository repository) : base(repository) 
    { 
    } 

所以Ninject不會知道如何構建一個通用的IRepository。你需要爲IRepository綁定一個實現。或在UserService中使用IUserRepository

public UserService(IUserRepository repository) : base(repository) 
    { 
    }