Hello,
I created a service application with a Rest service as follows:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class RestProductService
{
#region Constructors
public RestProductService()
{
NopConfig.Init();
IoC.InitializeWith(new DependencyResolverFactory());
}
#endregion
//.................
[WebGet(UriTemplate = "{id}")]
public ProductDataContract GetByProductId(string id)
{
var keeper = OperationContext.Current;
OperationContext.Current = null;
int productId = 0;
ProductDataContract dataContract = null;
Product product = null;
if (int.TryParse(id, out productId))
{
product = this.ProductService.GetProductById(productId);
//.............................
}
//.............................
OperationContext.Current = keeper;
return dataContract;
}//end of GetByProductId method
//I put this in here to use it as a property
public IProductService ProductService
{
get { return IoC.Resolve<IProductService>(); }
}
}//end of RestProductService class
In order to use the NopCommerce methods of ProductService, I had to do this before using them:
var keeper = OperationContext.Current;
OperationContext.Current = null;
and before returning, I had to restore the OperationContext.Current value:
OperationContext.Current = keeper;
Without these statements, I would get the cast error from NopObjectContext to IProductService (or to others like ICategoryService, ISettingsManager, etc) that some other people were also mentioning in their posts
e.g.
https://www.nopcommerce.com/boards/t/8378/unable-to-cast-object-of-type-nopcommercebusinesslogicdatanopobjectcontext-to-type-nopcommercebusinesslogicconfigurationsettingsisettingmana.aspx
https://www.nopcommerce.com/boards/t/8005/how-to-use-iocresolve-from-wcf.aspx
I also created a normal service and using the ProductService methods worked without any problem!
My question is: why this cast problem for wcf rest services? My fix by making null the OperationContext.Current (which is not really a fix though) suggests maybe a problem in the BusinessLogic/Infrastructure/UnityPerExecutionContextLifetimeManager or something related?
Looking forward to hearing from you guys,
Ada