2
\$\begingroup\$

Is it OK to mix different lifetime of ISerializer and ICacheProvider in this case? I am using Unity DI. In this case, whenever ICacheProvider is needed, Unity will always give the same instance (singleton) but ISerializer will always be a new instance. I am not sure if it would be OK to have ISerializer as a singleton as well in an ASP.NET Web API environment.

public class MyCacheProvider : ICacheProvider
{
   private readonly ISerializer _serializer;

   public MyCacheProvider(ISerializer serializer)
   {
       _serializer = serializer;
   }
}

Serializer implementation:

public class JilSerializer : ISerializer
    {
        public string Serialize<T>(T instance)
        {
            return JSON.Serialize(instance);
        }

        public T Deserialize<T>(string input)
        {
            return JSON.Deserialize<T>(input);
        }
    }

Configuring DI Container to provide instances:

container.RegisterType<ISerializer, JilSerializer>();
            container.RegisterType<ICacheProvider, MyCacheProvider>(new ContainerControlledLifetimeManager());
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Your MyCacheProvider will hold an instance of JilSerializer and since your MyCacheProvider is a singleton - there's going to be an instance of JilSerializer around forever as well.

As it's apparently fine for your ICacheProvider to use the same serializer throughout the lifetime of the app, and the implementation looks completely fine for sharing an instance, I don't see any reason why you can't just make ISerializer a singleton too.

I think that this isn't quite a captive dependency as the default lifetime of ISerializer is transient but it's certainly a related topic that you can read about on Mark Seemann's blog.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.