I have an api mvc project which for some of method when i call the action. it gives me an error like this:
{"Message":"An error has occurred.","ExceptionMessage":"An error occurred when trying to create a controller of type 'ReserveController'. 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.d__1.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Type 'Jabama.Web.API.Controllers.ReserveController' 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)"}}
Here is my api config class
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var container = new UnityContainer();
Jabama.Core.Services.Config.UnityConfig.RegisterTypes(container);
container.RegisterType<Core.Services.Search.IAutoCompoleteSearchService, Core.Services.Search.AutoCompoleteSearchService>();
container.RegisterType<Core.Services.Common.IImageService, Core.Services.Common.ImageService>();
container.RegisterType<Core.Services.Search.ICitySearchService, Core.Services.Search.CitySearchService>();
container.RegisterType<Core.Services.ContentPanel.ICityService, Core.Services.ContentPanel.CityService>();
container.RegisterType<IAuthenticationManager>(new InjectionFactory(o => new FakeOWINAuth()));
container.RegisterType<IDataProtectionProvider>(new InjectionFactory(o => Startup.DataProtectionProvider));
container.RegisterType<Core.Services.Common.IUserManagerService, Core.Services.Common.UserManagerService>();
container.RegisterType<Core.Services.FrontEnd.IOrderService, Core.Services.FrontEnd.OrderService>();
container.RegisterType<Core.Services.FrontEnd.IPlaceService, Core.Services.FrontEnd.PlaceService>();
CurrentUnityContainer.Container = container;
config.DependencyResolver = new UnityResolver(container);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Web API routes
config.MapHttpAttributeRoutes();
}
}
This is my CurrentUnityContainer
internal static class CurrentUnityContainer
{
internal static IUnityContainer Container { get; set; }
}
My UnityResolver
public class UnityResolver : IDependencyResolver
{
protected IUnityContainer container;
public UnityResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch (ResolutionFailedException ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return null;
}
}
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();
}
}
and this is my ReserveContoller which has been caused error in it
[RoutePrefix("v1/Reserve")]
public ReserveController(IOrderService orderService, IPaymentService paymentService, ISMSService smsService, IUserManagerService userService, IEventService eventService, ITourService tourService)
{
_orderService = orderService;
_paymentService = paymentService;
_smsService = smsService;
_userService = userService;
_eventService = eventService;
_tourService = tourService;
}
[Route("guests")]
[HttpPost]
[Authorize]
public async Task<UpdateResult<long>> SaveGuestInfo(long? orderId, long roomId, List<GuestInformationViewModel> guestList, string catKey, string placeKey, string checkIn, string checkOut ,Dictionary<string, string> rooms, string copoun , string guestRequirements)
{
//rooms : roomId-roomServiceId
Jabama.Core.Services.FrontEndViewModel.OrderViewModel order =
new Jabama.Core.Services.FrontEndViewModel.OrderViewModel();
order.OrderId = orderId ?? 0;
order.orderDetails =
new List<Jabama.Core.Services.FrontEndViewModel.OrderDetailsViewModel>();
VerifyOrderViewModel verifyOrder =_orderService.getVerifyOrder("fa", catKey,
placeKey, checkIn, checkOut, rooms, null, null, guestList);
bool isNewOrder = false;
if (order.OrderId == 0)
isNewOrder = true;
order.languageKey = verifyOrder.languageKey;
order.placeKey = verifyOrder.placeKey;
order.catKey = verifyOrder.catKey;
order.CheckIn = verifyOrder.CheckIn;
order.CheckOut = verifyOrder.CheckOut;
order.Copoun = copoun;
order.GuestRequirements = guestRequirements;
order.UserName = Thread.CurrentPrincipal.Identity?.Name;//verifyOrder.UserName;
string roomsName = "";
int j = 0;
int w = 0;
foreach (var od in verifyOrder.orderDetails)
{
for (int i = 0; i < od.RoomCount; i++)
{
var detail = new Jabama.Core.Services.FrontEndViewModel.OrderDetailsViewModel();
if (catKey == "tour")
{
detail.GuestInformation = guestList.Where(d => d.IsHeadMan == true).ToList()[w];
detail.GuestInformationId = guestList.Where(d => d.IsHeadMan == true).ToList()[w].Id;
}
else//hotel
{
detail.GuestInformation = guestList[j];
j++;
}
try
{
detail.AdultCount = (short)od.AdultCount;
detail.InfantCount = (short)od.InfantCount;
detail.ChildCount = (short)od.ChildCount;
}
catch (Exception)
{
}
detail.RoomId = od.RoomId;
detail.Capacity = od.Capacity;
detail.ExtraCapacity = od.ExtraCapacity;
detail.Breakfast = od.Breakfast;
detail.Dinner = od.Dinner;
detail.Lunch = od.Lunch;
detail.MenuType = od.MenuType;
order.orderDetails.Add(detail);
roomsName += od.RoomName.Replace("اتاق", "");
if (verifyOrder.orderDetails.Last() != od)
roomsName += ",";
}
w++;
}
var orderResult = await _orderService.GenerateOrder(order);
if (orderResult.IsSuccess)
{
if (isNewOrder)
{
new Thread(() =>
{
try
{
string userPhone = _userService.GetUserBy(order.UserName).PhoneNumber;
var notification = _eventService.GetEmailUsersForEvent("NewOrder");
double nights = 0;
if (!string.IsNullOrEmpty(verifyOrder.CheckIn) && !string.IsNullOrEmpty(verifyOrder.CheckOut))
nights = (verifyOrder.CheckOut.ToMiladiDateTime() - verifyOrder.CheckIn.ToMiladiDateTime()).TotalDays;
if (notification.RecevierNumber.Count() != 0)
{
_smsService.SendSMS(notification.RecevierNumber, string.Format(notification.SendedMessage, orderResult.ViewModel,
verifyOrder.PlaceName.Trim(),
verifyOrder.CheckIn,
nights,
verifyOrder.Phone1,
userPhone, roomsName, verifyOrder.CityName.Trim()), "NewOrder");
}
}
catch (Exception ex)
{
try
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
catch { }
}
}).Start();
}
return orderResult;
}
else
{
if (orderResult.StatusCode == 2)
{
return orderResult;
}
else if (orderResult.StatusCode == 3)
{
return orderResult;
}
else
{
return orderResult;
}
}
}
}
Does anyone have any ideas as to what's my mistake?
Thanks.