Refactoring ViewModelLocator with Autofac

After reviewing the way that I was constructing the IDataService and ISyncService implementations I figured that I wasn’t really leveraging Autofac very well. I realised that I could refactor the ViewModelLocator to at least look up the current implmentation, for example:

public ViewModelLocator()
{
    DataService= ServiceLocator.Current.GetInstance<IDataService>();
    SyncService = ServiceLocator.Current.GetInstance<ISyncService>();
}

Of course for this to work I have to register the types, which can be done in the ApplicationCore class since the implmentations of both interfaces are located in the Core library:

public class ApplicationCore
{
    public void Startup(Action<ContainerBuilder> dependencyBuilder)
    {
        var builder = new ContainerBuilder();

        builder.RegisterType<DataService>().SingleInstance().As<IDataService>();
        builder.RegisterType<SyncService>().SingleInstance().As<ISyncService>();

        dependencyBuilder(builder);

Note however, that whilst this is a bit of an improvement, the ViewModelLocator is still an example of a service locator, which is an anti-pattern (http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/). I’m yet to find a workable improvement that will still allow me to construct the ViewModelLocator in XAML.

Leave a comment