Skip to content

Instantly share code, notes, and snippets.

@brandonmartinez
Created December 10, 2012 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandonmartinez/1464286d648e73b339be to your computer and use it in GitHub Desktop.
Save brandonmartinez/1464286d648e73b339be to your computer and use it in GitHub Desktop.
StructureMapDependencyResolver
public class StructureMapDependencyResolver : System.Web.Http.Dependencies.IDependencyResolver
{
#region Fields
private readonly IContainer _container;
#endregion
#region Constructors
/// <summary>
/// </summary>
/// <param name="container"></param>
public StructureMapDependencyResolver(IContainer container)
{
_container = container;
}
#endregion
#region IDependencyResolver Members
/// <summary>
/// Starts a resolution scope.
/// </summary>
/// <returns>
/// The dependency scope.
/// </returns>
public IDependencyScope BeginScope()
{
return this;
}
public void Dispose()
{
// no-op since we return this for scopes
}
public object GetService(Type serviceType)
{
if (serviceType == null)
{
return null;
}
try
{
if (serviceType.IsAbstract || serviceType.IsInterface)
{
return _container.TryGetInstance(serviceType);
}
return _container.GetInstance(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAllInstances(serviceType).Cast<object>();
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment