首页 文章

发布Web Api时,依赖注入将停止工作

提问于
浏览
0

我有一个Web Api控制器,其中包含带参数的构造函数,如下所示:

public class UserController : ApiController
    {
        private UserService userService;
        public UserController(UserService userService)
        {
            this.userService = userService;
        }
}

我正在使用依赖注入 . 我跟着this tutorial,这就是它现在的样子:

public static class UnityConfig
    {
        public static void RegisterComponents()
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType<ITestService, TestService>();

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
    }
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            var container = new UnityContainer();
            container.RegisterType<UserService>().RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
            container.RegisterType<ProviderService>().RegisterType<UserService>().RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
            container.RegisterType<TransactionService>().RegisterType<UserService>().RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
            config.DependencyResolver = new UnityResolver(container);
...
}

当我从Visual Studio运行它并通过Postman进行测试时它工作得很好 . 但是当我发布Api并尝试从发布的版本运行它时,我收到此错误:

ExceptionMessage:尝试创建“UserController”类型的控制器时发生错误 . 确保控制器具有无参数的公共构造函数 .

en System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
en System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)
en System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

System.ArgumentException:类型'PaymentManagement.Web.Api.Controllers.UserController'没有预先确定的构造函数

en System.Linq.Expressions.Expression.New(Type type)
en System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)
en System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)
en System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)

这是我发布它的方式:
enter image description here

在添加Unity容器之前,我曾经从Visual Studio运行它时遇到同样的错误 . 但我不知道我现在缺少什么 .

1 回答

  • 0

    最后问题是EntityFramework.SqlServer.dll没有被添加到发布文件夹中 . 我找到了解决方案herehere

    通过将该DLL复制到我发布的API的bin文件夹,问题得到了解决 .

相关问题