Created
November 28, 2018 19:34
-
-
Save tuwukee/7b27ebb3fb1ab8403e08e6f962cce3bc to your computer and use it in GitHub Desktop.
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
// 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