지금은 Autofac의 IOC 컨테이너를 사용하여 Dependency Injection 패턴을 가르치려고합니다. 나는 아래에 제시된 아주 간단한 예를 생각해 냈다. 예제는 간단하지만 제대로 작동하지 않습니다.DI가있는 하나의 인터페이스에 대한 여러 구현
두 괴물, 모두 IMonster 인터페이스 구현 : 마지막으로
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();
}
}
그리고 내 주요 :
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!");
}
}
그럼 내 묘지 거기를 여기
내 클래스/인터페이스입니다
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)를 찾고있을 수도 있습니다. –
autofac은 묘화 클래스의 두 생성자 인수를 어떻게 해결합니까? – MattDavey
MattDavey의 정답입니다. 해석자가 생성자에 대해 Func 및 Func 의 특정 항목을 찾을 수 없으므로 null로 바꿉니다. 어쩌면 두 함수를 모두 리졸버에 등록하면 문제를 해결할 수 있습니다. –
Fendy