gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:42:57 24 4
gpt4 key购买 nike

我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com