使用Ninject的依赖性解析器

时间:2011-11-05 10:07:37

标签: asp.net asp.net-mvc-3 ninject

我总是收到错误 No parameterless constructor defined for this object. 当我执行下面的代码时。

它必须与我的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 个答案:

答案 0 :(得分:1)

已注册:

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

但您指的是IRepository中的基本UserService界面:

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

因此,Ninject将不知道如何构建通用IRepository。您需要绑定IRepository的实现。或者在IUserRepository中使用UserService

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