Skip to content

Instantly share code, notes, and snippets.

@jgeurts
Last active January 25, 2016 22:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jgeurts/2992401 to your computer and use it in GitHub Desktop.
Save jgeurts/2992401 to your computer and use it in GitHub Desktop.
StructureMap MVC 4 dependency resolver adapter
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.ServiceLocation;
using StructureMap;
// This is part of MvcKickstart (https://nuget.org/packages/mvckickstart)
namespace MvcKickstart.Infrastructure
{
/// <summary>
/// Wrapper for IDependencyScope, so that StructureMap plays nicely with built in mvc4 dependency resolution.
/// </summary>
public class StructureMapDependencyScope : ServiceLocatorImplBase
{
protected readonly IContainer Container;
public StructureMapDependencyScope(IContainer container)
{
if (container == null)
throw new ArgumentNullException("container");
Container = container;
}
public new object GetService(Type serviceType)
{
if (serviceType == null)
return null;
try
{
return serviceType.IsAbstract || serviceType.IsInterface
? Container.TryGetInstance(serviceType)
: Container.GetInstance(serviceType);
}
catch
{
return null;
}
}
/// <summary>
/// When implemented by inheriting classes, this method will do the actual work of resolving
/// the requested service instance.
/// </summary>
/// <param name="serviceType">Type of instance requested.</param>
/// <param name="key">Name of registered service you want. May be null.</param>
/// <returns>
/// The requested service instance.
/// </returns>
protected override object DoGetInstance(Type serviceType, string key)
{
if (string.IsNullOrEmpty(key))
{
return GetService(serviceType);
}
return Container.TryGetInstance(serviceType, key);
}
/// <summary>
/// When implemented by inheriting classes, this method will do the actual work of
/// resolving all the requested service instances.
/// </summary>
/// <param name="serviceType">Type of service requested.</param>
/// <returns>
/// Sequence of service instance objects.
/// </returns>
protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
{
return Container.GetAllInstances(serviceType).Cast<object>();
}
public IEnumerable<object> GetServices(Type serviceType)
{
return Container.GetAllInstances(serviceType).Cast<object>();
}
public void Dispose()
{
Container.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment