Last active
December 10, 2015 23:49
-
-
Save rmacfie/4512293 to your computer and use it in GitHub Desktop.
StructureMap + MVC4 + WebApi
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
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