Last active
August 29, 2015 13:57
-
-
Save davidbreyer/9640607 to your computer and use it in GitHub Desktop.
Use Microsoft Unity Dependency Injection with ServiceStack
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
//Update the Configure method of the AppHost to resemble the following. | |
public sealed class AppHost : AppHostBase | |
{ | |
public AppHost() | |
: base("ServiceStack", typeof(ExampleService).Assembly) | |
{ | |
} | |
public override void Configure(Container container) | |
{ | |
//register any dependencies your services use, e.g: | |
//container.Register<ICacheClient>(new MemoryCacheClient()); | |
//Create the IUnityContainer | |
IUnityContainer unityContainer = new UnityContainer(); | |
//register your objects | |
unityContainer.RegisterType<IExampleRepository, ExampleRepository>(); | |
//Create the Adapter | |
var unityAdapter = new UnityContainerAdapter(unityContainer); | |
//Add the new adapter to ServiceStack | |
container.Adapter = unityAdapter; | |
} | |
} | |
/// <summary> | |
/// IContainerAdapter for the unity framework. | |
/// </summary> | |
public class UnityContainerAdapter : IContainerAdapter | |
{ | |
private readonly IUnityContainer _unityContainer; | |
public UnityContainerAdapter(IUnityContainer container) | |
{ | |
_unityContainer = container; | |
} | |
public T Resolve<T>() | |
{ | |
return _unityContainer.Resolve<T>(); | |
} | |
public T TryResolve<T>() | |
{ | |
if (_unityContainer.IsRegistered(typeof(T))) | |
{ | |
return (T)_unityContainer.Resolve(typeof(T)); | |
} | |
return default(T); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment