很难让Unity依赖注入与WebAPI和OWIN一起工作



当我尝试在我的应用程序上调用控制器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)rn   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)rn   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)rn   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)rn   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
  }
} 

我的配置如下,我使用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:

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:

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:

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

我花了整个上午通过各种线程阅读,无法找出我错在哪里。如果我移除Unity并直接在控制器中实例化一个新的ProviderService,一切都可以正常工作。

我的问题是一个小疏忽。在Startup.cs中调用UseWebApi并没有将HttpConfiguration配置对象作为参数,而是声明了它自己的参数。这意味着WebAPI和Unity是用不同的HTTPConfiguration对象配置的,结果WebAPI不知道Unity。

答案已经在那里了!只是为了方便或更短的代码。

你可以写一个方法

    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:

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

然后添加UnityConfig.RegisterComponents();

最新更新