Web Api 发布后依赖注入停止工作

Dependency injection stops working when Web Api is published

我有一个 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: An error occurred when trying to create a controller of type 'UserController'. Make sure that the controller has a parameterless public constructor.

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: The type 'PaymentManagement.Web.Api.Controllers.UserController' doesn't have a predeterminate constructor

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)

这是我发布它的方式:

我曾经在添加统一容器之前从 Visual Studio 中 运行 时遇到同样的错误。但我不知道我现在错过了什么。

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

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