You can do this by plugging in a Dependency Injection container framework like Unity, Ninject, Autofac, Structure Map, etc and registering a service in the container and then injecting that service into your controller. There are Nuget packages for most of these DI frameworks to support Web API.
There is an example using Autofac here
However, using the same basic principle you can expose a service level object to controllers methods without using a DI Framework.
The idea is that you use a MessageHandler to insert your object instances to the Request Properties collection and then in the controller method pull it back out.
public class MyServiceHandler : DelegatingHandler
{
private readonly MyService _service;
public MyServiceHandler(MyService service)
{
_service = service;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Properties["MyService_Key"] = _service;
return base.SendAsync(request, cancellationToken);
}
}
In your configuration code you can add your message handler to the pipeline using,
config.MessageHandlers.Add(new MyServiceHandler(new MyService()));
and in your controller you can access the service like this,
public class StringsController : ApiController
{
/// <summary>
/// Get one entry from indexOfStrings
/// </summary>
public string Get(int listIndex)
{
var myService = Request.Properties["MyService_Key"] as MyService;
// How to return indexOfStrings[listIndex]?
var mystring = myService.GetMyString(99);
return "";
}
}
Ideally you should wrap up the access to your service in a helper method or a ApiController extension method, but those are just cosmetic details.
Now, you need to be careful, because MyService can now be called simultaneously on different threads. You need to ensure that you either use Concurrent collections for storing data or you use locks where necessary.