Created
April 2, 2014 07:48
-
-
Save hagbarddenstore/9929673 to your computer and use it in GitHub Desktop.
An implementation of the System.Web.Mvc.IDependencyResolver interface with StructureMap.
This file contains 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
namespace Hagbarddenstore.Mvc | |
{ | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Web.Mvc; | |
using StructureMap; | |
/// <summary> | |
/// Defines the StructureMapDependencyResolver type. | |
/// </summary> | |
public class StructureMapDependencyResolver : IDependencyResolver | |
{ | |
/// <summary> | |
/// The <see cref="IContainer"/>. | |
/// </summary> | |
private readonly IContainer _container; | |
/// <summary> | |
/// Initializes a new instance of the <see cref="StructureMapDependencyResolver"/> class. | |
/// </summary> | |
/// <param name="container"> | |
/// The container. | |
/// </param> | |
public StructureMapDependencyResolver(IContainer container) | |
{ | |
_container = container; | |
} | |
/// <summary> | |
/// Resolves singly registered services that support arbitrary object creation. | |
/// </summary> | |
/// <returns> | |
/// The requested service or object. | |
/// </returns> | |
/// <param name="serviceType"> | |
/// The type of the requested service or object. | |
/// </param> | |
public object GetService(Type serviceType) | |
{ | |
if (serviceType == null) | |
{ | |
return null; | |
} | |
try | |
{ | |
if (serviceType.IsAbstract || serviceType.IsInterface) | |
{ | |
return _container.TryGetInstance(serviceType); | |
} | |
return _container.GetInstance(serviceType); | |
} | |
catch (Exception exception) | |
{ | |
// TODO: Handle the exception? Elmah? | |
return null; | |
} | |
} | |
/// <summary> | |
/// Resolves multiply registered services. | |
/// </summary> | |
/// <returns> | |
/// The requested services. | |
/// </returns> | |
/// <param name="serviceType"> | |
/// The type of the requested services. | |
/// </param> | |
public IEnumerable<object> GetServices(Type serviceType) | |
{ | |
return _container.GetAllInstances(serviceType).Cast<object>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment