WebApi2与IoC

时间:2016-09-20 15:34:02

标签: c# dependency-injection asp.net-mvc-5 inversion-of-control unity-container

在我的MVC5应用程序中,我使用了NuGet中的 Unity.Mvc4 来管理我的依赖注入。

这会创建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>();
    }
  }

之后我在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
    }

我的常规Controller(例如HomeController)在向构造函数中注入任何内容都没有问题。但是,一旦我尝试在我的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);
    }
}

我尝试向此构造函数调用简单的GET请求我突然收到以下错误消息:

  

尝试创建类型的控制器时发生错误   'ValuesController'。确保控制器有一个   无参数公共构造函数。

我知道我需要在我的WebApiConfig下使用DependencyResolver做一些事情,但我不太确定是什么。以下是我班级现在的样子:

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 }
        );
    }
}

对此事项的任何帮助/建议都不胜感激。

1 个答案:

答案 0 :(得分:3)

您只配置了MVC依赖项解析程序,您也需要为Web API框架执行此操作。两个框架都有自己的依赖注入配置。

Initialise方法

中添加此内容
public static IUnityContainer Initialise()
    {
      var container = BuildUnityContainer();

      DependencyResolver.SetResolver(new UnityDependencyResolver(container));

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

      return container;
    }

您还需要安装Unity.WebAPI