Last active
August 29, 2015 14:07
-
-
Save coldacid/15ebbc16edd538f082d0 to your computer and use it in GitHub Desktop.
Common Service Locator adapter for TinyIoC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static void RegisterServices() | |
{ | |
var container = TinyIoCContainer.Current; | |
ServiceLocator.SetLocatorProvider(() => new TinyIoCServiceLocator(container)); | |
container.Register<ISettingsService>((c, o) => new CliOptionsSettingsService()); | |
// ... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.