难以在Unity ASP.NET Web API中构建具有注入依赖项的控制器

时间:2018-02-21 04:01:01

标签: c# asp.net .net asp.net-mvc unity-container

我知道在那里有类似的问题,但我花了好几个小时试图跟着他们无济于事,所以我真的很感激一些帮助。

我正在开发一个简单的ASP.NET MVC项目,我正在尝试将依赖项注入到带有Unity的Web API控制器中。基本结构是:

Web.config

EmailAccessor的构造函数需要从EmailController AppSettings中注入值。 NotificationEnginepublic 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; } //... } 只在其构造函数中包含一个对象。这是代码的删节版本:

EmailAccessor

public class NotificationEngine : INotificationEngine
{
    private IEmailAccessor emailAccessor;

    public NotificationEngine(IEmailAccessor emailAccessor)
    {
        this.emailAccessor = emailAccessor;
    }
    //...
}

NotificationEngine

[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)
    {
        //...
    }
    //...
}

EmailController

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

    }
}

UnityConfig

最后,这是我注册我的类型的类

<appSettings>

所有设置均来自Web.config中的localhost:63855/api/email/send

当我尝试POST到{ "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'." } 时,我收到以下回复:

for x in range(len(magic_word)):
    if guess == magic_word[x]:
        dashes[x] = guess

1 个答案:

答案 0 :(得分:1)

  

我正在开发一个简单的ASP.NET MVC项目,我试图将依赖项注入Web API控制器

它不是一个简单的ASP.NET MVC项目&#34;。它是一个包含ASP.NET MVC和Web API的混合项目,它是两个独立的框架。每个框架都有自己的类型和自己的配置。

您已使用ASP.NET MVC配置DI,但使用Web API 。要将这两个框架与DI一起使用,必须在项目中为两个框架设置依赖性解析器。

// MVC's DependencyResolver
DependencyResolver.SetResolver(new UnityDependencyResolver(container));

// Web API's DependencyResolver
GlobalConfiguration.Configuration.DependencyResolver 
    = new UnityDependencyResolver(container);

这假定您使用的UnityDependencyResolver实现System.Web.Http.Dependencies.IDependencyResolver。如果没有,则说明如何在Dependency Resolution with the Unity Container建立一个。

此外,请确保已启用属性路由,否则框架将不会拾取任何Web API属性路由。必须在应用程序启动时调用此方法。

GlobalConfiguration.Configure(config =>
{
    // ** Enable Attribute Routing for Web API **
    config.MapHttpAttributeRoutes();

    // For the config you are showing, you don't necessarily need this
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
});

如果没有解决问题,您应该another similar question查看答案。