Skip to main content
 首页 » 编程设计

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

2024年02月13日39yxwkf

我的 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; 
    } 
 
    ... 
}