Autofac Singleton Decorator constructed multiple times

Viewed 615

i'm trying to create a simple in-memory caching mechanism for some services. I'm using the Decorator pattern, creating a cached version of the service that decorates the concrete implementation of it. By using Autofac i will register the cache decorator as SingleInstance() in order to be sure that the data stays in memory.

 builder.RegisterDecorator<IBackendOperatorServiceProxy>(
      (c, inner) =>  new CachedBackendOperatorServiceProxy(inner), 
      fromKey: "BackendOperatorService")
      .SingleInstance();

and i will register the concrete implementation as

 builder.RegisterType<BackendOperatorServiceProxy>().Named<IBackendOperatorServiceProxy>("BackendOperatorService");

The problem that i'm having is that when resolved in the webApi controller, this singleton decorator is always recreated (once per request).

I have (hopefully) correctly set-up the owin pipeline for autofac (in fact the service gets injected in the BL class called by the controller).

I really can't understand a possible reason for an issue like this. I've used SIngleInstance() different times with different projects and it always worked without issues. To further "investigate" this i've also created a fake class registered as singleton and injected it in the same controller as the decorator. It works as expected, creating just a single instance of the fake class. For completeness, i've registered this fake one as:

builder.Register<Foo>(c => new Foo(c.ResolveNamed<IBackendOperatorServiceProxy>("BackendOperatorService"))).AsImplementedInterfaces().SingleInstance();

And this is the constructor of the Cached (Decorator) service:

public CachedBackendOperatorServiceProxy(IBackendOperatorServiceProxy decoratedServiceImplementation)
{
  _decoratedServiceImplementation = decoratedServiceImplementation ?? throw new ArgumentNullException(nameof(decoratedServiceImplementation));
  _cachedElements = new Dictionary<string, CachedOperatorDto>();
}

Is there any problem or something that i'm missing with decorators and SIngleInstances?

1 Answers

Thanks to Evk, the easiest solution is to just stick to "manual" decorator registration as RegisterDecorator (as reported in the link provided in comments) should be used when you need to decorate multiple implementations, not a single one as i was trying to do.

Related