Skip to content

Instantly share code, notes, and snippets.

@joaofx
Last active August 29, 2015 14:14
Show Gist options
  • Save joaofx/134c9e0fe6cddfb9754d to your computer and use it in GitHub Desktop.
Save joaofx/134c9e0fe6cddfb9754d to your computer and use it in GitHub Desktop.
Add and configure StructureMap in an ASP.NET MVC 5 Project
public class DependencyConfig
{
public static void RegisterDependencies()
{
var container = new Container();
container.Configure(cfg => cfg.Scan(scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
}));
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
}
}
DependencyConfig.RegisterDependencies();
public class StructureMapDependencyResolver : IDependencyResolver
{
private readonly IContainer _container;
public StructureMapDependencyResolver(IContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
if (serviceType.IsAbstract || serviceType.IsInterface)
{
// as the requested type is interface or abstract, tries to instance, if can't returns null
return _container.TryGetInstance(serviceType);
}
// instance a concrete type
return _container.GetInstance(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAllInstances<object>().Where(s => s.GetType() == serviceType);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment