0

I'm building a Worker Service who is a separated project from my main Web project. This Worker Service is responsible for consume RabbitMQ messages and send this message to MailSender. But, I'm not realizing how to register what I need as Dependency Injection. I figure out how to include these services in IoC, doing this:

// Create RabbitMQ connection to send as DI
container.Register<IModel>(() => CreateChannel(container), Lifestyle.Singleton);

container.Register<EmailConfig>(() => ConfigureMail(container), Lifestyle.Singleton);

container.Register<IEmailSender, EmailSender>(Lifestyle.Singleton);

The problem is that my Worker.cs have to receive ILogger<Worker>, EmailSender emailSender, IModel channel as DI and I figure out how to register my Email configurations, but I can't reach how to register these ILogger and IModel. So, my ConfigureServices from Startup.cs is like that:

var mailConfig = Configuration.GetSection("SMTP").Get<EmailConfig>();
services.AddSingleton(mailConfig );

var rabbitConfig = Configuration.GetSection("RabbitMQ").Get<RabbitMQConfig>();
services.AddSingleton(rabbitConfig);

services.AddSingleton<IEmailSender, EmailSender>();

IModel is from RabbitMQ (AMQP Model)

Isac Moura
  • 5,940
  • 3
  • 13
  • 27
  • What is `IModel` in this case? – Dai May 06 '20 at 01:55
  • If you're using `Microsoft.Extensions.Logging` then use MEL's DI registration method rather than registering it yourself. – Dai May 06 '20 at 01:56
  • @Dai IModel is from RabbitMQ.Client (AMQP Model) – Isac Moura May 06 '20 at 02:01
  • To register **open** generic types like `ILogger`, use `typeof(ILogger<>)` (yes, that's valid C#). Like so: `container.Register( typeof(ILogger<>), () => loggerFactory.CreateLogger( etc ) )` (but I've forgotten what to put for `etc`...) – Dai May 06 '20 at 02:07
  • I'm trying to do this to my WorkerService and I think the reference is not found `(container.Register(typeof(ILogger)` – Isac Moura May 06 '20 at 02:21
  • 1
    `ILogger` is a **closed** generic type, you need to use `typeof()` with an **open** generic type: `typeof(ILogger<>)`, don't use `typeof(ILogger)`. That's not a reference error. – Dai May 06 '20 at 02:23
  • This gives me: `'The given type ILogger is not a concrete type. Please use one of the other overloads to register this type. Arg_ParamName_Name'` – Isac Moura May 06 '20 at 02:36
  • That error message has the information you need - are you having problems understanding it? – Dai May 06 '20 at 02:37
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/213207/discussion-between-isac-moura-and-dai). – Isac Moura May 06 '20 at 02:40

0 Answers0