Skip to content

Instantly share code, notes, and snippets.

@komainu85
Created April 24, 2015 08:04
Show Gist options
  • Save komainu85/210df61e08b6864031e8 to your computer and use it in GitHub Desktop.
Save komainu85/210df61e08b6864031e8 to your computer and use it in GitHub Desktop.
Structure Map Dependency Resolver
public class StructureMapDependencyResolver : IDependencyResolver
{
private readonly IContainer _container;
public StructureMapDependencyResolver(IContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this._container = container;
}
public void Dispose()
{
_container.Dispose();
}
public object GetService(Type serviceType)
{
if (serviceType == null) return null;
try
{
if (serviceType.IsAbstract || serviceType.IsInterface)
{
return _container.TryGetInstance(serviceType);
}
else
{
return _container.GetInstance(serviceType);
}
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAllInstances<object>().Where(s => s.GetType() == serviceType);
}
public IDependencyScope BeginScope()
{
IContainer child = _container.GetNestedContainer();
return new StructureMapDependencyResolver(child);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment