我一直在我的Wep API2项目中使用NInject,目前为止没有问题,但我现在正在为一个奇怪的情况而苦苦挣扎。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”的控制器时发生错误。确保控制器有一个无参数的公共构造函数。
堆栈跟踪: 烯System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage请求,HttpControllerDescriptor controllerDescriptor,类型controllerType) 烯System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage请求) System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()
请问有人能指点我正确的方向吗?
谢谢!
请发布实际的错误转储。 – JuanR
另外,请发布其他两个参数的Ninject绑定。 – JuanR
嗨!执行错误转储如下:“尝试创建'UsersController'类型的控制器时发生错误,确保控制器具有无参数公共构造函数。” –