【发布时间】:2017-08-29 19:04:44
【问题描述】:
到目前为止,我一直在我的 Wep API2 项目中使用 NInject,没有出现任何问题,但我现在遇到了一个奇怪的情况。
我有一个控制器,它接收 3 个参数来设置它的依赖项。构造函数如下所示:
public UsersController(IUsersServices userServices, IConfigurationServices configServices, IUsersAPIProxy usersProxy)
{
this.configServices = configServices;
this.userServices = userServices;
this.usersProxy = usersProxy;
}
无法解决的依赖是最新的:IUsersAPIProxy。其他2没有问题。 当然,依赖项的绑定是这样定义的:
kernel.Bind<IUsersAPIProxy>().To<UsersAPIProxy>().InRequestScope();
kernel.Bind<IUsersServices>().To<UsersServices>().InRequestScope();
kernel.Bind<IConfigurationServices>().To<ConfigurationServices>().InRequestScope();
IUsersAPIProxy 接口非常简单:
public interface IUsersAPIProxy
{
UserModel ReadUser(string loginName);
IEnumerable<UserModel> ReadAllUsers();
}
UsersApiProxy 类没有任何需要注入的依赖:
public class UsersAPIProxy : APIProxyBase, IUsersAPIProxy
{
public IEnumerable<UserModel> ReadAllUsers()
{
var request = new RestRequest("sec/users2/");
IRestResponse<List<UserModel>> response = client.Execute<List<UserModel>>(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
return response.Data;
throw new ApplicationException(String.Format("There was an error when trying to retrieve the users. Response content: {0}"));
}
public UserModel ReadUser(string loginName)
{
var request = new RestRequest("sec/users2/{loginName}");
request.AddUrlSegment("loginName", loginName);
IRestResponse<UserModel> response = client.Execute<UserModel>(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
return response.Data;
throw new ApplicationException(String.Format("There was an error when trying to retrieve data for user {0}. Response content: {1}", loginName, response.Content));
}
}
它的基类也没什么特别的:
public class APIProxyBase
{
protected RestClient client = null;
public APIProxyBase()
{
client = new RestClient("http://myHost:MyPort/");
}
}
出于某种原因,我不知道我是否从控制器的构造函数中删除了 IUsersAPIProxy 参数,它按预期工作。奇怪的是,它只发生在这种依赖关系中。将参数更改为不同的位置当然无济于事。此外,实际工作的其他接口和类要复杂得多。 值得一提的是,有效的类型是在与无效的类型不同的 dll 中定义的。不用说,web api 正确地引用了这两个 dll。 我得到的异常如下:
消息: 尝试创建“UsersController”类型的控制器时发生错误。确保控制器有一个无参数的公共构造函数。
堆栈跟踪: zh System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) zh System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage 请求) zh System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()
有人能指点我正确的方向吗?
谢谢!
【问题讨论】:
-
请发布实际的错误转储。
-
另外,请发布其他两个参数的 Ninject 绑定。
-
嗨!实际的错误转储如下:“尝试创建'UsersController'类型的控制器时发生错误。确保控制器具有无参数的公共构造函数。”
-
工作的绑定是一样的,基本上是:kernel.Bind
().To ().InRequestScope(); kernel.Bind ().To ().InRequestScope(); -
请发布整个错误转储,而不仅仅是您认为可以提供帮助的部分。换句话说,请发布整个堆栈。请编辑您的问题,而不是将其添加为评论。
标签: c# asp.net-web-api2 ninject