Last active
August 29, 2015 14:14
-
-
Save joaofx/134c9e0fe6cddfb9754d to your computer and use it in GitHub Desktop.
Add and configure StructureMap in an ASP.NET MVC 5 Project
This file contains hidden or 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
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)); | |
} | |
} |
This file contains hidden or 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
DependencyConfig.RegisterDependencies(); |
This file contains hidden or 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
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