Web API 2 - Unity IOC - Instance per Instance by Application Variable

advertisements

I am using web api with unity IOC.

web api client passes client-id in request header and based on this value dependencies are resolved to create a external dll's method instance.

creation of this instance take around 6-7 seconds which is creating performance issues in web api.

What I want is to prevent instance creation for call with same client-id in header.

This is how I have implemented till now:-

//========================== ArchiveFactory ==========================
        ArchiveFactory archiverFactory = (HttpRequest httpRequest) =>
        {
            container.RegisterType<IArchive, Archive>("Archive",
            new HierarchicalLifetimeManager(),
            new InjectionConstructor(
                new ResolvedParameter<IStoreClient>(),
                Helper.GetArchiveContext(httpRequest))
                );
            return container.Resolve<IArchive>("Archive");
        };
        container.RegisterInstance(archiverFactory);

To be specific in my requirement - I am calling amazon services to retrieve images and there is a corporate dll which invokes amazon.


You can use caching mechanism at the controller/API layer(e.g Strathweb.CacheOutput.WebApi2) and you can decorate the controller method like this below. It's can cache based on parameter so if request comes in with same parameter, it will return results from cache.

[HttpGet]
[Route("")]
[CacheOutput(ServerTimeSpan = 60, ExcludeQueryStringFromCacheKey = true)]
public IHttpActionResult GetProducts(string clientId)
{
    var product = new List<Product>();
    return Ok(product);
}