autofac如何使用构造函数参数返回服务?

时间:2010-05-13 12:07:58

标签: autofac

我正在测试Autofac容器,如下所示:

var builder = new ContainerBuilder();

builder.Register(t => new TreatmentCenterRepository())
  .As<IRepository<TreatmentCenter>>();

builder.Register(t => new CreateTreatmentCenterCommandHandler(t.Resolve<IRepository<TreatmentCenter>>()))
  .As<ICommandHandler<CreateTreatmentCenterCommand>>();
var container = builder.Build();
var repo = container.Resolve<IRepository<TreatmentCenter>>();
var handler = container.Resolve<ICommandHandler<TreatmentCenter>>();

Console.WriteLine(repo);
Console.WriteLine(handler);

命令处理程序实现有一个带存储库参数的ctor。

当我运行时,我得到了这个例外:

Unhandled Exception: Autofac.Core.Registration.ComponentNotRegisteredException: The requested service 'Console
Application2.ICommandHandler`1[[ConsoleApplication2.TreatmentCenter, ConsoleApplication2, Version=1.0.0.0, Cul
ture=neutral, PublicKeyToken=null]]' has not been registered.
   at Autofac.ResolutionExtensions.Resolve(IComponentContext context, Service service, IEnumerable`1 parameter
s)
   at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context)
   at ConsoleApplication2.Program.Main(String[] args) in D:\Projects\Test Projects\ConsoleApplication2\Console
Application2\Program.cs:line 30

为什么要扒?我清楚地将该存储库注册为ctor param。

由于

1 个答案:

答案 0 :(得分:2)

异常消息表明问题:您正在尝试解析未在容器中注册的ICommandHandler<TreatmentCenter>。您在容器中拥有的内容是ICommandHandler<CreateTreatmentCenterCommand>。这可能是一个错字吗?