一個接口多個實現現在,我想教自己與Autofac的IOC容器的依賴注入模式。我提出了一個非常簡單的例子,下面將介紹這個例子。雖然這個例子很簡單,但我無法正常工作。與DI
這裏是我的類/接口:
兩個怪物,既實現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](https://code.google.com/p/autofac/wiki/TypedNamedAndKeyedServices)。 – 2013-04-11 08:09:29
autofac如何解析Graveyard類的兩個構造函數參數? – MattDavey 2013-04-11 08:11:41
MattDavey有一個正確的答案。似乎解析器無法找到兩個構造函數的Func和Func 的特定內容,因此替換爲null。也許註冊這兩個func到解析器都可以解決問題 –
Fendy
2013-04-11 08:15:17