c# - 当 ApiController 还需要空构造函数时使用依赖注入(inject)?

标签 c# asp.net-web-api unity-container

我的 MVC 网站的一个区域中有一个 ApiController,我通过 Unity 向它注入(inject)依赖项,我的 Controller 扩展了 System.Web.Http.ApiController。

我使用的是来自 Microsoft.Practices.Unity.dll v3.0.0.0 的 Unity。

我可以在 ApiAreaRegistration 中使用以下内容路由到 Controller

context.MapRoute(
    "Api_default",
    "Api/users/{action}/{id}"
);

但是我得到以下错误:

Type 'Project.Areas.Api.Controllers.UsersController' does not have a default constructor

但是,如果我添加默认构造函数,我的依赖项不会得到解析。

我开始觉得我缺少一些结构性的东西?

最佳答案

您没有显示您的 Controller 注册,错误消息表明您还没有注册 Controller 依赖项。

我使用 Unity.WebAPI NuGet 包负责 Controller 构建和容器生命周期管理。如果您的项目还使用 MVC Controller Unity.Mvc3将处理那些 Controller 。这些软件包只需很少的代码就可以为我的 Controller 连接 Unity。

我的 Unity Bootstrap 看起来像这样

public static class UnityConfig
{
    var container = BuildUnityContainer();

    // MVC controllers
    DependencyResolver.SetResolver(new Unity.Mvc3.UnityDependencyResolver(container));
    // WebAPI controllers
    GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
}

private static IUnityContainer BuildUnityContainer()
{
    var container = new UnityContainer();

    // register all your components with the container here
    // you don't need to register controllers
    container.RegisterType<IUsersService, UsersService>();
    ...
    return container;
}

而且我不担心我的 Controller 创建 -- 它只是工作。

public class UsersController : ApiController
{
    private IUsersService service;

    public UsersController(IUsersService service)
    {
        this.service = service;
    }

    ...
}

关于c# - 当 ApiController 还需要空构造函数时使用依赖注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18454074/

相关文章:

c# - Unity3D 新的 UI 系统和 ListView

c# - ASP.NET Core 移动后端 API [错误] : This appname. 找不到 azurewebsites.net 页面

javascript - 在 AngularJs 服务中从 Web Api 接收数据时出现问题

c# - 如何在 C# 中使用反射自定义方法列表

c# - Dispose() 是将数据保存到光盘的好地方吗?

c# - 在声明中存储信息

c# - Windows UI 自动化 : click tray icon button

c# - FromBody 值取空

c# - 带有 Unity Buildup<T> 问题的工厂模式

dependency-injection - 如何配置 Unity 为 IEnumerable 注入(inject)数组