开发者

How can autofac return service with constructor parameters?

开发者 https://www.devze.com 2022-12-29 23:36 出处:网络
I am testing out Autofac container with these below: var builder = new ContainerBuilder(); builder.Register(t => new TreatmentCenterRepository())

I am testing out Autofac container with these below:

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);

The command handler implementation has one ctor with repository parameter.

When I run this I get this exception:

Unha开发者_Go百科ndled 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

Why is it barfing? I clearly registered that handler with the repository as ctor param.

Thanks


The exception message indicates the problem: you are trying to resolve ICommandHandler<TreatmentCenter> which is not registered in the container. What you have in your container is ICommandHandler<CreateTreatmentCenterCommand>. Is it a typo perhaps?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号