Skip to content

Instantly share code, notes, and snippets.

@whyleee
Created May 20, 2016
Embed
What would you like to do?
StructureMap dependency resolver for Episerver with MVC/Web API
[ModuleDependency(typeof(EPiServer.Commerce.Initialization.InitializationModule))]
public class IocConfig : IConfigurableModule
{
public void ConfigureContainer(ServiceConfigurationContext context)
{
context.Container.EjectAllInstancesOf<ICatalogContentBuilder>();
context.Container.Configure(ConfigureContainer);
DependencyResolver.SetResolver(new StructureMap.StructureMapDependencyResolver(context.Container));
GlobalConfiguration.Configuration.DependencyResolver = new StructureMap.StructureMapDependencyResolver(context.Container);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;
using StructureMap;
namespace Website.App_Start.StructureMap
{
// NOTE: slightly modified version of 'StructureMapDependencyResolver' from 'StructureMap.MVC4' project
// https://github.com/webadvanced/Structuremap.MVC4/blob/master/content/DependencyResolution/StructureMapDependencyResolver.cs.pp
public class StructureMapDependencyResolver : StructureMapDependencyScope, IDependencyResolver, System.Web.Mvc.IDependencyResolver
{
public StructureMapDependencyResolver(IContainer container) : base(container) { }
public IDependencyScope BeginScope()
{
var childContainer = Container.GetNestedContainer();
return new StructureMapDependencyScope(childContainer);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;
using StructureMap;
namespace Website.App_Start.StructureMap
{
// NOTE: simplified version of 'StructureMapDependencyScope' from 'StructureMap.MVC4' project
// https://github.com/webadvanced/Structuremap.MVC4/blob/master/content/DependencyResolution/StructureMapDependencyScope.cs.pp
public class StructureMapDependencyScope : IDependencyScope
{
protected readonly IContainer Container;
public StructureMapDependencyScope(IContainer container)
{
Container = container;
}
public object GetService(Type serviceType)
{
return serviceType.IsAbstract || serviceType.IsInterface
? Container.TryGetInstance(serviceType)
: Container.GetInstance(serviceType);
}
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