Skip to content

Instantly share code, notes, and snippets.

@kidchenko
Created November 18, 2013 17:26
Show Gist options
  • Save kidchenko/7531748 to your computer and use it in GitHub Desktop.
Save kidchenko/7531748 to your computer and use it in GitHub Desktop.
Configuration Unity Container with ASP NET MVC
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));
}
}
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