Skip to content

Instantly share code, notes, and snippets.

@davidbreyer
Last active August 29, 2015 13:57
Show Gist options
  • Save davidbreyer/9640607 to your computer and use it in GitHub Desktop.
Save davidbreyer/9640607 to your computer and use it in GitHub Desktop.
Use Microsoft Unity Dependency Injection with ServiceStack
//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