【问题标题】:How can autofac return service with constructor parameters?autofac如何使用构造函数参数返回服务?
【发布时间】:2010-05-13 12:07:58
【问题描述】:

我正在使用以下这些测试 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 参数。

谢谢

【问题讨论】:

    标签: autofac


    【解决方案1】:

    异常消息表明问题:您正在尝试解决未在容器中注册的ICommandHandler&lt;TreatmentCenter&gt;。您在容器中拥有的是ICommandHandler&lt;CreateTreatmentCenterCommand&gt;。是不是笔误?

    【讨论】:

    • 你说得对,我的好先生。最后一条语句应该是“var handler = container.Resolve>();”感谢您指出这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 2015-04-06
    • 1970-01-01
    相关资源
    最近更新 更多