Reputation: 2639
I recently began experimenting with DI. I am using Unity Ioc to inject an EmailService from by Business Logic Layer into EmailServiceWrapper in the presentation layer which is then instantiated, my code is as follows:
public class EmailServiceWrapper : IIdentityMessageService
{
private readonly IEmailService _emailService;
public EmailServiceWrapper(IEmailService emailService)
{
this._emailService = emailService;
}
public async Task SendAsync(IdentityMessage message)
{
await _emailService.configSendGridasync(message.Body, message.Subject, new MailAddress(message.Destination));
}
}
I register the mapping like so:
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IEmailService, EmailServiceGmail>();
}
Finally in my ApplicationUserManager.cs I try to do the following:
appUserManager.EmailService = new EmailServiceWrapper(); //Dependency injection?
I get an error: "EmailServiceWrapper" does not have a constructor that takes 0 arguments. I am aware of what this means, but I am not sure how to set this up, I've seen many examples online about injecting dependencies into controllers but what about this case? Any help?
Upvotes: 1
Views: 44
Reputation: 2155
The aim of Unity is that you don't explicitly construct objects yourself, with all the inner constructors that would require; instead you get the container to do it for you:
appUserManager.EmailService = container.Resolve<EmailServiceWrapper>();
The point of
container.RegisterType<IEmailService, EmailServiceGmail>();
is to give the container the information it needs to new up any object that requires an IEmailService.
Upvotes: 3