简体   繁体   English

使用WebAPI和OWIN很难获得Unity依赖关系注入

[英]Difficulty getting Unity dependency injection working with WebAPI, and OWIN

When I try to call a controller API endpoint on my application I get this error: 当我尝试在应用程序上调用控制器API端点时,出现此错误:

   {
  "Message": "An error has occurred.",
  "ExceptionMessage": "An error occurred when trying to create a controller of type 'ProviderController'. Make sure that the controller has a parameterless public constructor.",
  "ExceptionType": "System.InvalidOperationException",
  "StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
  "InnerException": {
    "Message": "An error has occurred.",
    "ExceptionMessage": "Type 'mynamespace.api.controllers.ProviderController' does not have a default constructor",
    "ExceptionType": "System.ArgumentException",
    "StackTrace": "   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
  }
} 

My configuration is as follows and I am using the Unity.WebAPI library: 我的配置如下,并且我正在使用Unity.WebAPI库:

Startup.cs 启动文件

    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = GlobalConfiguration.Configuration;
        config.DependencyResolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());
        app.UseWebApi(WebApiConfig.Register());
        app.UseCors(CorsOptions.AllowAll);


        config.EnsureInitialized();

    }

UnityConfig.cs: UnityConfig.cs:

public static class UnityConfig
{
    #region Unity Container

    /// <summary>
    /// Load types in Unity Container 
    /// </summary>
    private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    /// <summary>
    /// Gets the configured Unity container.
    /// </summary>
    public static IUnityContainer GetConfiguredContainer()
    {
        return container.Value;
    }

    #endregion


    /// <summary>
    /// Register the types into Unity Container.
    /// </summary>
    /// <param name="container"></param>
    public static void RegisterTypes(UnityContainer container)
    {
        container.RegisterType<IProviderService, ProviderService();  
    } 
}

ProviderController.cs: ProviderController.cs:

public class ProviderController : ApiController
{
    private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
    private readonly IProviderService providerService;      

    public ProviderController(IProviderService providerService)
    {
        providerService = providerService;
    }

    //Controller API Methods
}

ProviderService.cs: ProviderService.cs:

    public ProviderService()
    {
        this.serviceClient = new ServiceClientAdapter();
    }

I have spent all morning reading through various threads and am unable to figure out where I am going wrong. 我整个上午都在阅读各种内容,无法弄清楚我要去哪里。 If I remove Unity and instantiate a new ProviderService directly in the controller, everything works. 如果我删除Unity并直接在控制器中实例化一个新的ProviderService,则一切正常。

My problem was a small oversight. 我的问题是小疏忽。 The call to UseWebApi in Startup.cs was not taking the HttpConfiguration config object as a parameter but was instead declaring it's own. 在Startup.cs中对UseWebApi的调用未将HttpConfiguration配置对象作为参数,而是声明了它自己的。 This meant that WebAPI and Unity were configured with different HTTPConfiguration objects and the WebAPI was not aware of Unity as a result. 这意味着WebAPI和Unity配置了不同的HTTPConfiguration对象,因此WebAPI不知道Unity。

Answer is already there! 答案已经在那里! Just for easiness or shorter code. 只是为了简单起见或更短的代码。

You can write single method 您可以编写单个方法

    public static void RegisterComponents()
    {
        var container = new UnityContainer();

        // register all your components with the container here
        // it is NOT necessary to register your controllers

        container.RegisterType<IProviderService, ProviderService>();

        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }

Startup.cs: Startup.cs:

    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);
        HttpConfiguration config = GlobalConfiguration.Configuration;
        app.UseWebApi(config);
    }

Then add UnityConfig.RegisterComponents(); 然后添加UnityConfig.RegisterComponents(); into Global file 进入全局文件

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

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