lundi 16 janvier 2017

Service Locator Pattern in C#: freaky code?

I decided to use a Service Locator pattern in my prj. However I suspect that the current code is freaky. The thing is: I have 3 types but the 3rd one uses the first 2, so it seems to me that the code is not ok, how could I improve it?

Here's the code:

public class ServiceLocator: IServiceLocator
{
    private static ServiceLocator _instance;

    private IDictionary<object, object> services;

    private ServiceLocator()
    {
        services = new Dictionary<object, object>();

        this.services.Add(typeof(IService1), new Service1());
        this.services.Add(typeof(IService2), new Service2());
        this.services.Add(typeof(IService3), new Service3(new Service1(), new Service2(), new Service4()));
    }

    public static ServiceLocator Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new ServiceLocator();
            }
            return _instance;
        }
    }

    public T GetService<T>()
    {
        return (T)services[typeof(T)];
    }
}

Aucun commentaire:

Enregistrer un commentaire