Skip to content

Instantly share code, notes, and snippets.

@wshaddix
Created July 29, 2014 23:30
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 wshaddix/7a6b888a722dcd944ac0 to your computer and use it in GitHub Desktop.
Save wshaddix/7a6b888a722dcd944ac0 to your computer and use it in GitHub Desktop.
A custom dependency resolver for Asp.Net MVC 5 that utilizes StructureMap for dependency resolution
using Microsoft.Practices.ServiceLocation;
using StructureMap;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Insiders.Web.Infrastructure.IoC
{
public class StructureMapDependencyResolver : ServiceLocatorImplBase
{
private const string StructuremapNestedContainerKey = "Structuremap.Nested.Container";
public IContainer Container { get; set; }
private HttpContextBase HttpContext
{
get
{
var ctx = Container.TryGetInstance<HttpContextBase>();
return ctx ?? new HttpContextWrapper(System.Web.HttpContext.Current);
}
}
public IContainer CurrentNestedContainer
{
get { return (IContainer)HttpContext.Items[StructuremapNestedContainerKey]; }
set { HttpContext.Items[StructuremapNestedContainerKey] = value; }
}
public StructureMapDependencyResolver(IContainer container)
{
Container = container;
}
protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
{
return (CurrentNestedContainer ?? Container).GetAllInstances(serviceType).Cast<object>();
}
protected override object DoGetInstance(Type serviceType, string key)
{
var container = (CurrentNestedContainer ?? Container);
if (string.IsNullOrEmpty(key))
{
return serviceType.IsAbstract || serviceType.IsInterface
? container.TryGetInstance(serviceType)
: container.GetInstance(serviceType);
}
return container.GetInstance(serviceType, key);
}
public void Dispose()
{
if (CurrentNestedContainer != null)
{
CurrentNestedContainer.Dispose();
}
Container.Dispose();
}
public IEnumerable<object> GetServices(Type serviceType)
{
return DoGetAllInstances(serviceType);
}
public void DisposeNestedContainer()
{
if (CurrentNestedContainer != null)
CurrentNestedContainer.Dispose();
}
public void CreateNestedContainer()
{
if (CurrentNestedContainer != null) return;
CurrentNestedContainer = Container.GetNestedContainer();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment