asp.net将ApiController添加为依赖项注入服务 [英] asp.net adding ApiController as service for dependency injection

查看:485
本文介绍了asp.net将ApiController添加为依赖项注入服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我离开了

Hello I went off this guide to integrate asp.net core Dependency Injection into MVC 5. Originally it worked fine using a default controller (Inherited from System.Web.Mvc.Controller class). But then I wanted the injected dependency to be available in an controller that inherited from System.Web.Http.ApiController. I'm 95% sure the problem is coming from this part of the code where all the controllers are added as services since I'm getting the same error as the guide says I will get without it that portion.

缺少的方法异常,说明您的构造函数未实现默认的无参数构造函数

a missing method exception saying that your constructor doesn’t implement the default parameterless constructor

Startup.cs

public static class ServiceProviderExtensions
{
   public static IServiceCollection AddControllersAsServices(this IServiceCollection services,
      IEnumerable<Type> controllerTypes)
   {
      foreach (var type in controllerTypes)
      {
         services.AddTransient(type);
      }

      return services;
   }
}

public partial class Startup
{
  public void ConfigureServices(IServiceCollection services){
    PackageScraperService pScraper = new PackageScraperService();
    services.addSington<IPackageScraper>(pScraper);

    // Problem Code

    services.AddControllersAsServices(typeof(Startup).Assembly.GetExportedTypes()
     .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
     .Where(t => typeof(IController).IsAssignableFrom(t) 
        || t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));
  }

  public void Configuration(IAppBuilder app){
      var services = new ServiceCollection();

      ConfigureServices(services)
      var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());
      DependencyResolver.SetResolver(resolver);
  }
}

我查看了

typeof(Startup).Assembly.GetExportedTypes()
     .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
     .Where(t => typeof(IController).IsAssignableFrom(t) 
        || t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))

它似乎可以正确找到我的ApiController(ValuesController.cs)

and it appears to correctly find my ApiController (ValuesController.cs)

我还更改了我的api控制器,使其继承自Controller类,并且工作正常.

I also changed my api controller to inherit from the Controller class and it worked fine.

是否有更简单的方法将控制器添加为服务?自从我使用MVC而不是Core以来,为此一直很难找到文档.

Is there a simpler way to add a controller as a service? I've had a incredibly hard time finding documentation for this since I'm using MVC instead of Core.

推荐答案

更新为包含ApiControllers

services.AddControllersAsServices(typeof(Startup).Assembly.GetExportedTypes()
     .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
     .Where(t => typeof(IController).IsAssignableFrom(t) 
        || typeof(IHttpController).IsAssignableFrom(t));

您还需要为Web API全局配置设置依赖性解析器.

You will also need to set the dependency resolver for the Web API global configuration.

更新DefaultDependencyResolver,以便MVC和Web API均可使用.它们通过名称共享一个接口,但是它们属于不同的命名空间.

Update the DefaultDependencyResolver so that it can be used by both MVC and Web API. They share an interface by name but they belong to different namespaces.

public class DefaultDependencyResolver :
    System.Web.Http.Dependencies.IDependencyResolver,
    System.Web.Mvc.IDependencyResolver {

    private readonly IServiceProvider serviceProvider;

    public DefaultDependencyResolver(IServiceProvider serviceProvider) {
        this.serviceProvider = serviceProvider;
    }    

    public object GetService(Type serviceType) {
        return this.serviceProvider.GetService(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType) {
        return this.serviceProvider.GetServices(serviceType);
    }

    //Web API specific

    public System.Web.Http.Dependencies.IDependencyScope BeginScope() {
        return this;
    }

    public void Dispose() {
        // NO-OP, as the container is shared. 
    }
}

然后在启动时为MVC和Web API设置解析器.

And in start up you set the resolver for both MVC and Web API.

public void Configuration(IAppBuilder app){
    var services = new ServiceCollection();    
    ConfigureServices(services);        
    var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());
    DependencyResolver.SetResolver(resolver);//Set MVC
    GlobalConfiguration.Configuration.DependencyResolver = resolver; //Set for Web API
}

这篇关于asp.net将ApiController添加为依赖项注入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆