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

时间:2016-10-18 18:14:08

标签: c# asp.net dependency-injection visual-studio-2015 unity-container

我有一个带控制器的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 :(得分:0)

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

通过将该dll复制到我发布的API的bin文件夹中,问题得到解决。