This project is read-only.

HttpOperationHandler & DI

Topics: Web Api
Jan 11, 2012 at 2:36 PM
Edited Jan 11, 2012 at 2:36 PM

Hey there. 

Please let me know if there is a better, more accurate place to do this in the case that it applies.
I have an HttpRequestHandler in which I want to be able to gain access to a container in which I have wired into my DI mechanism (Autofac).  Is there any pay to pass interfaces to my containers / repositories into my HttpOperationHandler?
The reason I am wanting to do this is to do some basic validation against header information coming in.  For the sake of this example, lets say that I want to check to make sure the header "userid" exists in the header.  Additionally I want to use a repository that I have to make sure that the "userid" passed in via the header is authorized.  I have an interface for my repository in which I am using throughout the application and using IoC's to new up the correct repositories for me.

Can I do something like this? (I know the answer, it just might make more sense with an example)
        protected override string OnHandle(System.Net.Http.HttpRequestMessage input1, IUserRepository input2)
            if (!input1.Headers.Contains("userid"))
                throw new Exception("user id does not exist");
                string userid = input1.Headers.GetValues("userid").First();
                if (!input2.IsValidUser(userid))
                    throw new Exception("User id is not valid");
                    return userid;

Obviously this will not work, however I think you might get what the idea behind this HttpOperationHandler is trying to do.  Because the HttpOperationHandler gets included in the HttpConfiguration object the way it does it is making it very tricky for me to use DI to drive specific behaviors on the HttpOperationHandler. 

Is there a way to accomplish what I am trying to do here? 
Is there a way to accomplish what I am trying to do here another way? 

Thanks for any help in advance!

Jan 11, 2012 at 3:03 PM

You can pass data to your operation handlers for example via the constructor, just send your container instance that way?

For example:

// Response Handlers
config.ResponseHandlers = (handlers, endpoint, operation) =>
    handlers.Add(new ContentTypeHandler(operation));  // This could as well be a member variable in the method where you are defining your config
Jan 11, 2012 at 4:01 PM

Thanks for the reply.

I got this one figured out.  I can ask my IoC container to resolve what I want and pump it into the constructor as you said.

Thanks a bunch!