Self host web api in Orchard

Topics: Core, Customizing Orchard, General, Nederlands (Dutch), Writing modules
Sep 19, 2013 at 6:56 AM
I want to use a self hosted web api controller in Orchard (for internal communication in a webfarm). The web api controller must have an empty constructor. Is there an (easy) way to resolve and use objects that are normally passed by the constructor?
Sep 19, 2013 at 7:06 AM
Yes, you should be able to get the current WorkContext from the controller, which you can then use to resolve services. I wrote a little article that might help: http://skywalkersoftwaredevelopment.net/blog/orchard-webapi-global-actionfilters-and-dependency-injection.

Although it shows how to do it from a filter attribute, the idea is the same.
Sep 19, 2013 at 7:46 AM
Edited Sep 19, 2013 at 9:53 AM
Thank you for the article!

I copied your code, but the GetWorkContext() method returns an empty workcontext. I tried it in the Api Controller and in the Filter like your example. Did I miss something or it is because I use a selfhosted webapi?
public class TriggerFilter : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
       var workContext = actionContext.ControllerContext.GetWorkContext();
    }
}

[TriggerFilter]
public class FarmSyncController : ApiController
{
    public String GetTrigger(string signal)
    {
         return signal;
      }
}
Sep 19, 2013 at 9:58 AM
When debugging it does not get a value for the IWorkContextAccessor from the routeData values.
object workContextValue;
if (!routeData.Values.TryGetValue("IWorkContextAccessor", out workContextValue)) {
        return null;
}