Skip to content

Instantly share code, notes, and snippets.

@prabirshrestha
Created June 16, 2011 12:05
Show Gist options
  • Save prabirshrestha/1029105 to your computer and use it in GitHub Desktop.
Save prabirshrestha/1029105 to your computer and use it in GitHub Desktop.
Unity MVC 3 Dependency Resolver
using System.Configuration;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
[assembly: WebActivator.PreApplicationStartMethod(typeof(WebApplication.App_Start.AppStart_Unity), "Start")]
namespace WebApplication.App_Start
{
public class AppStart_Unity
{
public static void Start()
{
// Create unity container
var container = new UnityContainer();
// register services with the container.
RegisterServices(container);
// Tell MVC 3 to use Unity DI container.
DependencyResolver.SetResolver(
serviceType =>
{
try { return container.Resolve(serviceType); }
catch { return null; }
},
serviceType =>
{
try { return container.ResolveAll(serviceType); }
catch { return null; }
});
// Register Unity with Common Serivice Locator also
Microsoft.Practices.ServiceLocation.ServiceLocator.SetLocatorProvider(
() => new UnityServiceLocator(container));
}
public static void RegisterServices(IUnityContainer container)
{
// register types here
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment