Skip to content

Instantly share code, notes, and snippets.

@tuwukee
Created November 28, 2018 19:34
Show Gist options
  • Save tuwukee/7b27ebb3fb1ab8403e08e6f962cce3bc to your computer and use it in GitHub Desktop.
Save tuwukee/7b27ebb3fb1ab8403e08e6f962cce3bc to your computer and use it in GitHub Desktop.
// Within the Application_Start() event handler in the Global.asax.cs
ControllerBuilder.Current.SetControllerFactory(new DependencyControllerFactory());
ObjectFactory.Initialize(registry => registry
.ForRequestedType<IContactRepository>()
.TheDefaultIsConcreteType<ContactManagerLinqRepository>());
// The repository class which is passed through DI to the controller
public class ContactManagerEntityRepository : IContactRepository
{
public IList<Contact> GetContacts()
{
ContactManagerEntities entities = new ContactManagerEntities();
return entities.ContactSet.ToList();
}
}
// The IoC
using System;
using System.Web.Mvc;
using StructureMap;
namespace ContactManager.IoC
{
public class DependencyControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(Type controllerType)
{
return ObjectFactory.GetInstance(controllerType) as Controller;
}
}
}
// The controller itself
public class ContactController : Controller
{
private readonly IContactRepository iRepository;
public ContactController(IContactRepository repository)
{
iRepository = repository;
}
public ActionResult Index()
{
return View(iRepository.GetContacts());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment