Created
November 18, 2013 17:26
-
-
Save kidchenko/7531748 to your computer and use it in GitHub Desktop.
Configuration Unity Container with ASP NET MVC
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 MvcApplication : System.Web.HttpApplication | |
{ | |
protected void Application_Start() | |
{ | |
// *** Other Configurations *** | |
UnityConfiguration(); | |
} | |
public void UnityConfiguration() | |
{ | |
IUnityContainer container = new UnityContainer(); | |
container.RegisterType(typeof(IExample), typeof(Example)); | |
container.RegisterType(typeof(IOtherExample), typeof(OtherExample)); | |
DependencyResolver.SetResolver(new UnityDependencyResolver(container)); | |
} | |
} |
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 UnityDependencyResolver : IDependencyResolver | |
{ | |
private readonly IUnityContainer _container; | |
public UnityDependencyResolver(IUnityContainer container) | |
{ | |
_container = container; | |
} | |
public object GetService(Type serviceType) | |
{ | |
try | |
{ | |
return _container.Resolve(serviceType); | |
} | |
catch | |
{ | |
return null; | |
} | |
} | |
public IEnumerable<object> GetServices(Type serviceType) | |
{ | |
try | |
{ | |
return _container.ResolveAll(serviceType); | |
} | |
catch | |
{ | |
return new List<object>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment