KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Right now I'm trying to teach myself the Dependency Injection pattern with the IOC-container from Autofac. I've come up with a very simple example, which is presented below. Although the example is simple, I fail to get it working properly. Here are my classes/interfaces: Two monsters, both implementing the IMonster interface: interface IMonster { void IntroduceYourself(); } class Vampire : IMonster { public delegate Vampire Factory(int age); int mAge; public Vampire(int age) { mAge = age; } public void IntroduceYourself() { Console.WriteLine("Hi, I'm a " + mAge + " years old vampire!"); } } class Zombie : IMonster { public delegate Zombie Factory(string name); string mName; public Zombie(string name) { mName = name; } public void IntroduceYourself() { Console.WriteLine("Hi, I'm " + mName + " the zombie!"); } } Then there's my graveyard: interface ILocation { void PresentLocalCreeps(); } class Graveyard : ILocation { Func<int, IMonster> mVampireFactory; Func<string, IMonster> mZombieFactory; public Graveyard(Func<int, IMonster> vampireFactory, Func<string, IMonster> zombieFactory) { mVampireFactory = vampireFactory; mZombieFactory = zombieFactory; } public void PresentLocalCreeps() { var vampire = mVampireFactory.Invoke(300); vampire.IntroduceYourself(); var zombie = mZombieFactory.Invoke("Rob"); zombie.IntroduceYourself(); } } And finally my main: static void Main(string[] args) { // Setup Autofac var builder = new ContainerBuilder(); builder.RegisterType<Graveyard>().As<ILocation>(); builder.RegisterType<Vampire>().As<IMonster>(); builder.RegisterType<Zombie>().As<IMonster>(); var container = builder.Build(); // It's midnight! var location = container.Resolve<ILocation>();
Tags (comma-separated)
Save Edits
Cancel