【问题标题】:Using Unity with Web Api 2 gives error does not have a default constructor将 Unity 与 Web Api 2 结合使用会导致错误没有默认构造函数
【发布时间】:2016-05-08 07:07:55
【问题描述】:

我有 ASP.NET MVC5 Web 应用程序,并且我在同一个应用程序中也有 Web API。我正在为 DI 使用 Unity(版本 4)。 我在APP启动时配置Unity容器如下

        public class MvcApplication : System.Web.HttpApplication
        {
            protected void Application_Start()
            {
                UnityConfiguration.Config();
            }
        }

        public class UnityConfiguration()
        {
         public void Config()
         {
                UnityContainer container = new UnityContainer();
                container.RegisterType<IMyService, Myservice>();
                container.RegisterType<IGenericRepository, GenericRepository>();
                container.RegisterType<DbContext, MyEntities>();            
         }
        }

        public class GenericRepository:IGenericRepository
        {
           private DbContext _dbcontext;
           public GenericRepository(DbContext dbcontext)
           {
               _dbcontext = dbcontext;
           }
        }
        public class MyService:IMyService
        {
           private IGenericRepository _repo;
           publi void MyService(IGenericRepository repository)
           {
              _repo = repository;
           }
        }


        public class MyApiController:ApiController
        {
           provate IMyService _service;
           MyApiController(IMyService myservice)
           {
              _service = myservice;
           }

           public IEnumerable<MyModel> GetData()
           {
             var result = _service.GetData();
             return result.ConvertToMyModel();
           }
        }

但是,当我像

一样调用 url
localhost://lookup/getdata

我得到错误

类型“LookupController”没有默认构造函数

我该如何解决这个问题?我需要用 Unity 注册我创建的每个控制器还是 Unity 会自动注册所有 MVC 控制器?

【问题讨论】:

  • 您必须创建自己的IControllerFactoryIControllerActivator 实现(并在MVC 和Web API 中注册它们)或实现自己的IDependencyResolver(两个框架都有自己的IDependencyResolver 抽象) 并注册这些。
  • @steven 谢谢。但是我发现有 Unity.MVC5 和 Unity.Webapi 包 avalble..但是也有用于 ASP.NET MVC 的 Unity 引导程序......所以不确定使用哪一个

标签: asp.net-mvc dependency-injection asp.net-web-api2 unity-container


【解决方案1】:

我倾向于使用Unity.Mvc-package。

您不需要注册控制器,但您需要使用 WebAPI 注册 Unity。

   public class UnityConfiguration()
   {
       public IUnityContainer Config()
       {
            IUnityContainer container = new UnityContainer();
            container.RegisterType<IMyService, Myservice>();
            container.RegisterType<IGenericRepository, GenericRepository>();
            container.RegisterType<DbContext, MyEntities>(); 

            // return the container so it can be used for the dependencyresolver.  
            return container;         
       }
    }

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Your routes...

            // Register Unity with Web API.
            var container = UnityConfiguration.Config();
            config.DependencyResolver = new UnityResolver(container);

            // Maybe some formatters?
        }
    }

你还需要一个 DependencyResolver:

public class UnityResolver : IDependencyResolver
{
    protected IUnityContainer container;

    public UnityResolver(IUnityContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }
        this.container = container;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new UnityResolver(child);
    }

    public void Dispose()
    {
        container.Dispose();
    }
}

你也可以看看这个类似的问题,除了 Owin 部分。 Unity.WebApi | Make sure that the controller has a parameterless public constructor

【讨论】:

  • UnityMvcActivator 现在是否处理 Unity 与 Web API 的注册?这是你回答后出现的东西吗?
  • @janh 这是在 config.DependencyResolver = ... 行中完成的
  • 谢谢,我知道代码示例就是这样做的。我刚刚安装了 unity web api 包,似乎包含了一个激活器,这意味着您不再需要手动配置依赖解析器
【解决方案2】:

我有同样的错误,就我而言,问题是我忘记注册一个依赖项,我为依赖注入注册的类之一在构造函数中注入。

在您的示例中,您是否向 MyEntities 中注入了您忘记注册的内容?

【讨论】:

    【解决方案3】:

    安装 Nuget 包 Unit.WebAP 而不是 Unity.MVC5 确保使用 nuget 安装了正确的统一包

    我安装了 Unity.MVC5 并面临类似的异常“无参数构造函数”

      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>();
            container.RegisterType<ICar, Tesla>();
            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 2016-03-28
      相关资源
      最近更新 更多