My Asp.net mvc web api project have unity controller,it’s packages information is bellow
<package id="Unity" version="4.0.1" targetFramework="net451" />
<package id="Unity.Mvc" version="4.0.1" targetFramework="net451" />
After install those library from nuget manager I get two files in my App_Start folder they are respectively
1) UnityConfig.cs
2) UnityMvcActivator.cs
After write come content on my web api controller when I compile and run it’s show me bellow error.
{"$id":"1","Message":"An error has occurred.","ExceptionMessage":"An error occurred when trying to create a controller of type 'UserInfoController'. 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)\
To resolve this error, I used unity build in resolver in my UnityConfig.cs file syntax is bellow
public static void RegisterTypes(IUnityContainer container)
{
container
.RegisterType<IDataContextAsync, SmartHomeDataContext>(new PerRequestLifetimeManager())
.RegisterType<IUnitOfWorkAsync, UnitOfWork>(new PerRequestLifetimeManager())
.RegisterType<IVersionService, VersionService>()
.RegisterType<IRepositoryAsync<Model.Models.Version>, Repository<Model.Models.Version>>()
.RegisterType<IUserInfoService, UserInfoService>()
.RegisterType<IRepositoryAsync<Model.Models.UserInfo>, Repository<Model.Models.UserInfo>>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
Error is remaining,then I follow this article and try to use his manually create resolver.When I use article used resolver my application compiled with bellow error.
What should I do,how to solve this parameter less constructor issue.Will I need to use Unity web api nugget.
My Controller is bellow:
public class UserInfoController : ApiController
{
private readonly IUnitOfWorkAsync _unitOfWorkAsync;
private readonly IUserInfoService _userInfoService;
public UserInfoController(IUnitOfWorkAsync unitOfWorkAsync, IUserInfoService userInfoService)
{
this._unitOfWorkAsync = unitOfWorkAsync;
this._userInfoService = userInfoService;
}
[Route("api/Userinfos")]
public HttpResponseMessage Get()
{
Mapper.CreateMap<UserInfo, UserInfoEntity>();
var userInfos = _userInfoService.GetsUserInfos();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, Mapper.Map<IEnumerable<UserInfo>, IEnumerable<UserInfoEntity>>(userInfos));
return response;
}
}