Last active
August 29, 2015 14:03
-
-
Save StacyGay/5de53a15fe3d7badd48e to your computer and use it in GitHub Desktop.
DependencyResolver Example
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
public class DependencyResolver : IDependencyResolver | |
{ | |
private readonly SessionContainerManager _containerManager; | |
public DependencyResolver(SessionContainerManager containerManager) | |
{ | |
_containerManager = containerManager; | |
} | |
protected IUnityContainer ChildContainer | |
{ | |
get | |
{ | |
return _containerManager.GetContainer(); | |
} | |
} | |
public void DisposeOfChildContainer() | |
{ | |
_containerManager.DisposeContainer(); | |
} | |
private bool IsRegistered(Type typeToCheck) | |
{ | |
var isRegistered = true; | |
if (typeToCheck.IsInterface || typeToCheck.IsAbstract) | |
{ | |
isRegistered = ChildContainer.IsRegistered(typeToCheck); | |
if (!isRegistered && typeToCheck.IsGenericType) | |
{ | |
var openGenericType = typeToCheck.GetGenericTypeDefinition(); | |
isRegistered = ChildContainer.IsRegistered(openGenericType); | |
} | |
} | |
return isRegistered; | |
} | |
public object GetService(Type serviceType) | |
{ | |
if (typeof(IController).IsAssignableFrom(serviceType)) | |
{ | |
return ChildContainer.Resolve(serviceType); | |
} | |
return IsRegistered(serviceType) ? ChildContainer.Resolve(serviceType) : null; | |
} | |
public IEnumerable<object> GetServices(Type serviceType) | |
{ | |
if (IsRegistered(serviceType)) | |
{ | |
yield return ChildContainer.Resolve(serviceType); | |
} | |
foreach (var service in ChildContainer.ResolveAll(serviceType)) | |
{ | |
yield return service; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment