12

我尝试运行以下代码:

using System.Web.Http;
using System.Web.Mvc;
using Conduit.Mam.ClientSerivces.Dal.Configuration;
using MamInfrastructure.Common.Dal;
using MamInfrastructure.Common.Logger;
using MamInfrastructure.Logger;
using Microsoft.Practices.Unity;
using Unity.WebApi;

namespace Conduit.Mam.ClientServices.Common.Initizliaer
{
    public static class Initializer
    {
        private static bool isInitialize;
        private static readonly object LockObj = new object();
        private static IUnityContainer defaultContainer = new UnityContainer();

        static Initializer()
        {
            Initialize();
        }

        public static void Initialize()
        {
            if (isInitialize)
                return;

            lock (LockObj)
            {
                IUnityContainer container = defaultContainer;

                //registering Unity for web API
                GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
                //registering Unity for MVC
                DependencyResolver.SetResolver(new UnityDependencyResolver(container));

                container.RegisterType<IDal<ClientService.DAL.EntityFramework.MamConfiguration>, MamConfigurationDal>();
                container.RegisterType<IApplicationLogger, Log4NetLogger>();

                if (!isInitialize)
                {
                    isInitialize = true;
                }
            }
        }
    }
}

广告得到以下异常:

The type Unity.WebApi.UnityDependencyResolver does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator. Parameter name: commonServiceLocator

我试图安装 webApi 包,但它没有帮助

4

2 回答 2

27

在您的Initialize方法中替换:

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

和:

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

现在你明白问题是什么了:

System.Web.Http.Dependencies.IDependencyResolver(由 Web APISystem.web.Mvc.IDependencyResolver使用)和(由 ASP.NET MVC 使用)是两种完全不同的类型(即使它们具有相同的名称),但是您尝试将它们都分配给相同的类型 ( UnityDependencyResolver),这显然无法正常工作。

于 2012-12-23T18:12:13.053 回答
11

我遇到了类似的问题,但就我而言,我的 Web 应用程序具有 MVC 和 WebApi 控制器。我这样解决:

using Microsoft.Practices.Unity;
using System.Web.Http;
using System.Web.Mvc;
using Unity.Mvc5;

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

第一行将使用 MVC DependencyResolver,在第二行中我使用 WebApi UnityDependencyResolver。

于 2014-07-08T08:26:40.277 回答