0

I'm trying to avoid usage of Service Locator. The previous code looks like:

public class UnitOfWork
{
    private T CreateRepository<T>(T repo) 
        where T : 
        IRepository
    {
        return ServiceLocator.Current.GetInstance<T>();
    }
}

I am using Autofac as IoC. I dont wanna useILifetimeScopeorIContainer` or similar. Can you please share your ideas on how to implement in an elegant way creating a generic method of creating repositories without a usage of Service Locator and an introduction of IoC dependencies?

Cyril Durand
  • 15,834
  • 5
  • 54
  • 62
Victor
  • 201
  • 3
  • 10

1 Answers1

1

Whether or not you are applying the Service Locator anti-pattern, depends on where this code is located, because:

A DI container encapsulated in a Composition Root is not a Service Locator - it's an infrastructure component.

In other words, in case your UnitOfWork is placed inside the Composition Root, you are not applying the Service Locator anti-pattern and your code is fine.

Of course, this would make it impossible for application code to call CreateRepository, since the Composition Root depends on all other code in your solution, while nothing depends on the Composition Root.

This problem however is easily solved by extracting an interface out of this class and placing this interface in the layer that requires its use. For instance:

// Core layer
public interface IUnitOfWork
{
    T CreateRepository<T>() where T : IRepository;
}

// Composition Root
public class UnitOfWork : IUnitOfWork
{
    // ...
}
Steven
  • 166,672
  • 24
  • 332
  • 435