我是 ASP.NET WebApi 项目的新手,但希望我能把所有内容都做得足够直接。创建几个CRUD控制器之后,我想到了一个绝妙的想法 - 为所有这些编写通用的基础CRUD-web-API控制器,并且不要重写相同的代码。
在成功实现这样的类后,我遇到了依赖解析的问题,这对于非泛型/非继承控制器仍然有效。
简单请求(GET,POST等)给出:
的 Type 'UsersController' does not have a default constructor","ExceptionType":"System.ArgumentException"
没有注射的默认构造函数工作正常。显然我的Ninject配置有问题。
public abstract class BaseCRUDController<T> : ApiController where T : class, IClientEntity
{
private readonly Repository<T> _repo;
private readonly IDbContextDataProvider _context;
// With this ctor everything works well
public BaseCRUDController()
{
this._context = new ModelContext();
this._repo = new Repository<T>(this._context);
}
// Injection is not working ((
public BaseCRUDController(IDbContextDataProvider context)
{
this._context = context;
this._repo = new Repository<T>(context);
}
Controller
实体的具体User
:
public class UsersController : BaseCRUDController<User>
{
UsersController(IDbContextDataProvider context) : base(context) { }
UsersController() : base() { }
}
Ninject配置自己:
public class DataProviderModule : NinjectModule
{
public override void Load()
{
this.Bind<IDbContextDataProvider>().To<ModelContext>().InSingletonScope();
}
}
public class NinjectResolver
{
// Instantinate Ninject dependencies resolver
public static System.Web.Http.Dependencies.IDependencyResolver GetConfiguredDependencyResolver()
{
IKernel kernel = new StandardKernel(new DataProviderModule());
System.Web.Http.Dependencies.IDependencyResolver njResolver = new NinjectResolver(kernel);
return njResolver;
}
}
Application_Start
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
var config = GlobalConfiguration.Configuration;
config.DependencyResolver = NinjectResolver.GetConfiguredDependencyResolver();
WebApiConfig.Register(config);
我在这里做错了什么?
<小时/> 注意:如果我有以下方法,这种方法很有效:
public class UsersController : ApiController
{
UsersController(IDbContextDataProvider context)
{
....
}
...
答案 0 :(得分:1)
哦..我花了好几个小时尝试不同的方法。这很疯狂。这里有趣的部分是Ninject
运行良好,代码正确,除了一个辅助功能修饰符。向public
ctor添加UsersController
修饰符可解决此问题。
public class UsersController : BaseCRUDController<User>
{
public UsersController(IDbContextDataProvider context) : base(context) { }
...
PS。仔细编写代码......