1

I came across this piece of code:

public class SomeServiceFactory : ISomeServiceFactory
{
    private IUnityContainer container;

    public SomeServiceFactory(IUnityContainer unityContainer)
    {
        this.container = unityContainer;
    }

    public virtual ISomeService GetSomeService()
    {
        return this.container.Resolve<ISomeService>();
    }
}

I'm trying to understand how this pattern is more useful then simply having the consumer of this factory simply be injected with ISomeService directly? Thus, become a consumer of the service itself, rather than the factory. What does this additional layer of indirection achieve, as implemented here?

I understand that if the creation of ISomeService needed more intricate logic, not achievable by container.Resolve, then definitely a factory would have been required.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
Asif Shiraz
  • 864
  • 1
  • 12
  • 27

1 Answers1

1

Good question. Without contextual information, it's difficult to defend such a degenerate Abstract Factory.

Sometimes, the reason for this may be that the programmer writing the consumer of this factory knew that the ISomeService implementation had to be created anew for each use; perhaps that particular implementation wasn't thread-safe.

Furthermore, ISomeService might derive from IDisposable, and perhaps the client does something like this:

using (var svc = this.factory.GetSomeService())
{
    // use svc here...
}

This would cause svc to be properly disposed of after use.

All of the above are leaky abstractions, but common nonetheless.

A better approach to deal with such lifetime and resource management issues is either via a Decoraptor or the Register Resolve Release pattern.

This, however, could still require you to have a class like SomeServiceFactory, but then it'd be an infrastructure component, for example supporting a Decoraptor.


Do note, however, that this particular Abstract Factory is degenerate because it takes no method arguments. An Abstract Factory with one or more method arguments, on the other hand, is a common solution to the problem of creating a polymorphic service based on a run-time value.

Community
  • 1
  • 1
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736