确保控制器在Web API中具有无参数的公共构造函数? [英] Make sure that the controller has a parameterless public constructor in web api?
问题描述
我正在努力解决使用 uniy 进行依赖项注入的问题.我已根据此链接实现 https://www.asp.net/web-api/overview/advanced/dependency-injection
I am struggling with this problem of dependency injection using untiy. I have implemented according to this link https://www.asp.net/web-api/overview/advanced/dependency-injection
但是出现了这个错误:
{
"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred when trying to create a controller of type 'WebAPIController'. Make sure that the controller has a parameterless public constructor.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": " at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Type 'Fairmoves.Controllers.WebAPIController' does not have a default constructor",
"ExceptionType": "System.ArgumentException",
"StackTrace": " at System.Linq.Expressions.Expression.New(Type type)\r\n at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
}
}
我的Web Api控制器:
My Web Api Controller:
[RoutePrefix("api/WebAPI")]
public class WebAPIController : ApiController
{
private readonly IUserBusinessService UserBusinessService;
private readonly ILoginBusinessService LoginBusinessService;
//public WebAPIController():base()
//{
//}
public WebAPIController(IUserBusinessService UserBusinessService, ILoginBusinessService LoginBusinessService)
{
this.UserBusinessService = UserBusinessService;
this.LoginBusinessService = LoginBusinessService;
}
[HttpPost]
public IHttpActionResult Login([FromBody]AuthModels.LoginModel model)
{
// string strUserId = credentials.LoginName;
//string strPassword = credentials.Password;
var serviceResultDAO1 = LoginBusinessService.LoginUserSubmit(model.LoginName);
}
}
UnityResolver.cs :
public class UnityResolver:IDependencyResolver
{
protected IUnityContainer container;
public UnityResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
[DebuggerStepThrough]
public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
[DebuggerStepThrough]
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}
public IDependencyScope BeginScope()
{
var child = container.CreateChildContainer();
return new UnityResolver(child);
}
public void Dispose()
{
container.Dispose();
}
}
}
WebApiConfig.cs :
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//config.DependencyResolver = new NinjectResolver();
var container = new UnityContainer();
container.RegisterType<ILoginBusinessService, LoginBusinessService>(new HierarchicalLifetimeManager());
container.RegisterType<IUserBusinessService, UserBusinessService>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
//DependencyResolver.SetResolver(new UnityDependencyResolver(container));
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
无法确定问题出在哪里?能否请您进入代码并让我知道. 我关注了以下所有这些链接
Unable to identify where the problem is? Can please get into the code and let me know. I have followed all these below links
但是这些都不能解决我的问题.
But none of these solved my problem.
推荐答案
As i am using both MVC and WebAPI in one project, i understood by using this link that i need to resolve both dependencies.
因此,我删除了WebAPIConfig.cs文件中的以下代码
So, i removed below code in WebAPIConfig.cs file
var container = new UnityContainer();
container.RegisterType<ILoginBusinessService, LoginBusinessService>(new HierarchicalLifetimeManager());
container.RegisterType<IUserBusinessService, UserBusinessService>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
在我的项目中安装了一个名为 Unity.WebAPI 的软件包之后.
After i installed one package called Unity.WebAPI in my project.
在UnityConfig.cs文件中添加了以下代码
Added below code in UnityConfig.cs file
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
就是这样,解决了我的问题!
That's it, solved my problem!
这篇关于确保控制器在Web API中具有无参数的公共构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!