【发布时间】:2013-04-03 08:10:10
【问题描述】:
现在我正在尝试使用 Autofac 的 IOC 容器自学依赖注入模式。我想出了一个非常简单的例子,如下所示。尽管示例很简单,但我无法使其正常工作。
这是我的类/接口:
两个怪物,都实现了 IMonster 接口:
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!");
}
}
然后是我的墓地:
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();
}
}
最后是我的主要内容:
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>();
location.PresentLocalCreeps();
// Waiting for dawn to break...
Console.ReadLine();
container.Dispose();
}
这是我的问题: 在运行时,Autofac 在这一行抛出异常:
var vampire = mVampireFactory.Invoke(300);
似乎 mVampireFactory 实际上是在尝试实例化一个僵尸。当然这是行不通的,因为僵尸的构造函数不会采用 int。
有没有简单的方法来解决这个问题? 还是我理解 Autofac 的工作方式完全错误? 你会如何解决这个问题?
【问题讨论】:
-
我想你可能正在寻找Named Services。
-
autofac 如何解析 Graveyard 类的两个构造函数参数?
-
MattDavey 有一个正确的答案。似乎解析器无法为两个构造函数找到 Func
和 Func 的特定内容,因此用 null 替换。也许将这两个函数都注册到解析器中可以解决问题
标签: c# .net dependency-injection inversion-of-control autofac