Nick A Miller
Nick A Miller

Reputation: 1325

How do I share long lived resources between multiple controllers in Web API?

I have a WebAPI controller class (inheriting from ApiController).

It needs to read data which which exists on disk. I don't want to load from disk for every request.

So I'd like to find some way to inject the dependency into the controller.

Should I create a custom dependency resolver implementing IDependencyResolver?

What thread safety measures do I need to take for my dependency class?

Upvotes: 0

Views: 67

Answers (1)

Mihail Stancescu
Mihail Stancescu

Reputation: 4138

You can use ninject to inject the dependency to any controllers you need.

To use the dependency injection for web api you need an other nuget package for ninject called "WebApiContrib.IoC.Ninject".

Ninject creates a file calle "NinjectWebCommon.cs" in you App_Start folder where you can configure your dependencies.

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<ILogLivedResource>().To<LongLiveResourceInstance>().InRequestScope();;
}

More information you can find here.

Regards, Mishu

Upvotes: 1

Related Questions