I know there are similar questions for this out there, but I've spent hours trying to follow them to no avail so I would really appreciate some help.
I'm working on a simple ASP.NET MVC project, and I'm trying to inject dependencies into a Web API Controller with Unity. The basic structure is:
EmailController <- NotificationEngine <- EmailAccessor
EmailAccessor's constructor needs to have injected values from Web.config
AppSettings. EmailController
and NotificationEngine
only take a single object in their constructors. Here's an abridged version of the code:
EmailAccessor
public class EmailAccessor : IEmailAccessor
{
private string senderEmail;
private string senderUsername;
private string senderPassword;
private int port;
public EmailAccessor(string senderEmail, string senderUsername, string senderPassword, int port)
{
this.senderEmail = senderEmail;
this.senderUsername = senderUsername;
this.senderPassword = senderPassword;
this.port = port;
}
//...
}
NotificationEngine
public class NotificationEngine : INotificationEngine
{
private IEmailAccessor emailAccessor;
public NotificationEngine(IEmailAccessor emailAccessor)
{
this.emailAccessor = emailAccessor;
}
//...
}
EmailController
[RoutePrefix("api/email")]
public class EmailController : ApiController
{
private INotificationEngine notificationEngine;
public EmailController(INotificationEngine notificationEngine)
{
this.notificationEngine = notificationEngine;
}
[HttpPost]
[Route("send")]
public void Post([FromBody] EmailNotification email)
{
//...
}
//...
}
UnityConfig
Finally, here's the class where I register my types
public static class UnityConfig
{
public static void RegisterTypes(IUnityContainer container)
{
container.LoadConfiguration();
//...
container.RegisterType<IEmailAccessor, EmailAccessor>(new InjectionConstructor(
ConfigurationManager.AppSettings["SenderEmail"],
ConfigurationManager.AppSettings["SenderUsername"],
ConfigurationManager.AppSettings["SenderPassword"],
int.Parse(ConfigurationManager.AppSettings["Port"])));
container.RegisterType<INotificationEngine, NotificationEngine>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
The settings are all pulled from <appSettings>
in Web.config
.
When I try and POST to localhost:63855/api/email/send
, I get the following response:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:63855/api/email/send'.",
"MessageDetail": "No type was found that matches the controller named 'email'."
}