简体   繁体   English

带有IoC的WebApi2

[英]WebApi2 with IoC

In my MVC5 application I have used Unity.Mvc4 from NuGet to manage my dependency injection. 在我的MVC5应用程序中,我使用来自NuGet的Unity.Mvc4来管理我的依赖项注入。

This creates Bootstrapper.cs which looks like following: 这将创建Bootstrapper.cs ,如下所示:

  public static class Bootstrapper
  {
    public static IUnityContainer Initialise()
    {
      var container = BuildUnityContainer();

      DependencyResolver.SetResolver(new UnityDependencyResolver(container));

      return container;
    }

    private static IUnityContainer BuildUnityContainer()
    {
      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>();    
      RegisterTypes(container);

      return container;
    }

    public static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<IUnitOfWork, ApplicationDbContext>();
    }
  }

Afterwards I initialize Unity under Global.asax.cs like following: 之后,我在Global.asax.cs下初始化Unity,如下所示:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        Bootstrapper.Initialise(); // < ----- here
    }

My regular Controller (eg HomeController) has no issues with injecting anything into it's constructor. 我的常规Controller (例如HomeController)在向其构造函数中注入任何内容都没有问题。 However once I try to inject anything in my ApiController which is located in the same project like this: 但是,一旦我尝试在位于相同项目的ApiController注入任何内容,如下所示:

public class ValuesController : ApiController
{
    private readonly IUnitOfWork _repository;

    public ValuesController(IUnitOfWork repository)
    {
        _repository = repository;
    }

    public IEnumerable<PatientData> Get()
    {
        return _repository.Repository.ReturnResults();
    }

    public HttpResponseMessage Get(string id)
    {
        var patient = _repository.Repository.FindById(Convert.ToInt32(id));

        return Request.CreateResponse(HttpStatusCode.OK, patient);
    }
}

and I try to call simple GET request to this constructor I suddenly receive the following error message: 并且我尝试对此构造函数调用简单的GET请求,突然收到以下错误消息:

An error occurred when trying to create a controller of type 'ValuesController'. 尝试创建“ ValuesController”类型的控制器时发生错误。 Make sure that the controller has a parameterless public constructor. 确保控制器具有无参数的公共构造函数。

I know there is something I need to do something with DependencyResolver under my WebApiConfig , but I am not quite sure what. 我知道我需要在WebApiConfig下使用DependencyResolver进行WebApiConfig ,但是我不太确定该做什么。 Here is how my class looks like now: 这是我的班级现在的样子:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Any help / suggestions in this matter would be more than appreciated. 在此问题上的任何帮助/建议将不胜感激。

You have configured only the MVC dependency resolver, you need to do it also for the Web API framework too. 您仅配置了MVC依赖关系解析器,还需要针对Web API框架进行配置。 Both frameworks have their own dependency injection configurations. 这两个框架都有自己的依赖项注入配置。

Add this in the Initialise method Initialise方法中添加它

public static IUnityContainer Initialise()
    {
      var container = BuildUnityContainer();

      DependencyResolver.SetResolver(new UnityDependencyResolver(container));

      GlobalConfiguration.Configuration.DependencyResolver = 
                    new Unity.WebApi.UnityDependencyResolver(container);

      return container;
    }

You also need to install the Unity.WebAPI package 您还需要安装Unity.WebAPI软件包

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM