Skip to content

Instantly share code, notes, and snippets.

@rmacfie
Last active December 10, 2015 23:49
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 rmacfie/4512293 to your computer and use it in GitHub Desktop.
Save rmacfie/4512293 to your computer and use it in GitHub Desktop.
StructureMap + MVC4 + WebApi
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;
using StructureMap;
public class StructureMapResolver : IDependencyScope, IDependencyResolver
{
private readonly IContainer _container;
private readonly bool _isContainerOwner;
public StructureMapResolver(IContainer container) : this(container, false)
{
}
public StructureMapResolver(IContainer container, bool isContainerOwner)
{
_container = container;
_isContainerOwner = isContainerOwner;
}
public IDependencyScope BeginScope()
{
return new StructureMapResolver(_container.GetNestedContainer(), isContainerOwner: true);
}
public object GetService(Type serviceType)
{
if (serviceType == null)
{
return null;
}
if (serviceType.IsAbstract || serviceType.IsInterface)
{
return _container.TryGetInstance(serviceType);
}
return _container.GetInstance(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAllInstances(serviceType).Cast<object>();
}
public void Dispose()
{
if (_isContainerOwner)
{
_container.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment