Skip to content

Instantly share code, notes, and snippets.

@coldacid
Last active August 29, 2015 14:07
Show Gist options
  • Save coldacid/15ebbc16edd538f082d0 to your computer and use it in GitHub Desktop.
Save coldacid/15ebbc16edd538f082d0 to your computer and use it in GitHub Desktop.
Common Service Locator adapter for TinyIoC
static void RegisterServices()
{
var container = TinyIoCContainer.Current;
ServiceLocator.SetLocatorProvider(() => new TinyIoCServiceLocator(container));
container.Register<ISettingsService>((c, o) => new CliOptionsSettingsService());
// ...
}
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.ServiceLocation;
using TinyIoC;
namespace CommonServiceLocator.TinyIoCAdapter
{
class TinyIoCServiceLocator : IServiceLocator
{
private readonly TinyIoCContainer _container;
public TinyIoCServiceLocator(TinyIoCContainer container)
{
_container = container ?? TinyIoCContainer.Current;
}
public TinyIoCServiceLocator() : this(null) { }
public IEnumerable<TService> GetAllInstances<TService>()
{
return _container.ResolveAll(typeof (TService), true).Cast<TService>();
}
public IEnumerable<object> GetAllInstances(Type serviceType)
{
return _container.ResolveAll(serviceType, true);
}
public TService GetInstance<TService>(string key)
{
return (TService)_container.Resolve(typeof (TService), key);
}
public TService GetInstance<TService>()
{
return (TService) _container.Resolve(typeof (TService));
}
public object GetInstance(Type serviceType, string key)
{
return _container.Resolve(serviceType, key);
}
public object GetInstance(Type serviceType)
{
return _container.Resolve(serviceType);
}
public object GetService(Type serviceType)
{
return _container.Resolve(serviceType);
}
}
}
@coldacid
Copy link
Author

coldacid commented Oct 3, 2014

TinyIoC is a great little one-file IoC container for when you don't need or want the power of a full-sized system. However, if you use assemblies that rely on CommonServiceLocator for getting their own dependencies, you'll quickly find that there's no adapter for TinyIoC. This class provides a simple adapter so that you can use TinyIoC with CSL-using assemblies and services.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment