2

I have a solution with an MVC application and a Web API. They're in separate projects and domains (using CORS). I built it as a Web API to have the flexibility for adding consumers but currently my MVC application is the only consumer. As such I'm debating whether to use HttpClient inside my MVC Controller or directly instantiate the ApiController.

In either case, I'm using dependency injection (Autofac) so I'd also like to know how to configure that because neither HttpClient or ApiController have any kind of interface that I can inject through constructor parameters like I usually do so I'm not sure how to handle this.

What should the lifetime scopes be for the injected instance? HttpClient should probably be Singleton since it's not encouraged to dispose it after each request.

NOTE By calls to the API return large datasets used to populate charts which is why I'm leaning a bit away from HttpClient as I feel I will incur additional overhead using Http. Is it an antipattern to directly instantiate the ApiController?

Thanks

parliament
  • 21,544
  • 38
  • 148
  • 238
  • What was wrong with your [old question](http://stackoverflow.com/questions/15849595/consuming-web-api-apicontroller-or-httpclient-using-dependency-injection)? – nemesv Apr 06 '13 at 20:07
  • Sorry, this is a show stopper atm I don't know how to proceed. – parliament Apr 06 '13 at 20:11
  • If instantiating an `ApiController` would solve your problem why don't you move the logic from the `ApiController` to a separate service class and just inject the service and use it from both of your controllers? – nemesv Apr 06 '13 at 20:15

1 Answers1

4

You could always do this

var httpClient = new HttpClient(new HttpServer(GlobalConfiguration.Configuration));

This allows you to continue using the HttpClient but the requests get passed directly to the WebApi server without ever making a network request. This way if you later decide to separate out your WebAPI your client code doesn't change

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • Thank you for the response. This looks like a viable option but I'd like to know more about this type of call. Can you say more or share a link where I can read more. How can I prevent instantiating these 2 objects on each request I believe they're both quite expensive to create? And what do you mean by your last sentence, isn't my API already separate? – parliament Apr 07 '13 at 06:34