勁爆經典大帝國I(AWESOME CLASSIC MIX VOL.1)

2013/03/24

2013.03.24 - ASP.Net Web API...使用Ninject問題


做個筆記...
當開啟Web API專案,使用Ninject來做DI的話,可能會出現像下例的錯誤訊息


怎麼解決這個問題呢,首先打開NuGet,安裝Ninject.Web.Common


安裝完在你的App_Start目錄會多一個檔案"NinjectWebCommon.cs"
這個Class透過WebActivator來做初始化及釋放
所以安裝時也會一併參考WebActivator

接著新增一個類別,這邊取作"NinjectDependencyScope.cs"
using Ninject;
using Ninject;
using Ninject.Syntax;
using System;
using System.Web.Http.Dependencies;

namespace MvcApplication1.App_Start
{
    // Provides a Ninject implementation of IDependencyScope
    // which resolves services using the Ninject container.
    public class NinjectDependencyScope : IDependencyScope
    {
        IResolutionRoot resolver;

        public NinjectDependencyScope(IResolutionRoot resolver)
        {
            this.resolver = resolver;
        }

        public object GetService(Type serviceType)
        {
            if (resolver == null)
                throw new ObjectDisposedException("this", "This scope has been disposed");

            return resolver.TryGet(serviceType);
        }

        public System.Collections.Generic.IEnumerable<object> GetServices(Type serviceType)
        {
            if (resolver == null)
                throw new ObjectDisposedException("this", "This scope has been disposed");

            return resolver.GetAll(serviceType);
        }

        public void Dispose()
        {
            IDisposable disposable = resolver as IDisposable;
            if (disposable != null)
                disposable.Dispose();

            resolver = null;
        }

    }

    // This class is the resolver, but it is also the global scope
    // so we derive from NinjectScope.
    public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
    {
        IKernel kernel;

        public NinjectDependencyResolver(IKernel kernel)
            : base(kernel)
        {
            this.kernel = kernel;
        }

        public IDependencyScope BeginScope()
        {
            return new NinjectDependencyScope(kernel.BeginBlock());
        }
    }
}

然後編輯"NinjectWebCommon.cs",在CreateKernel時,去指定GlobalConfiguration.Configuration.DependencyResolver...
最後就在RegisterServices加入要做DI的程式碼...


這樣就沒問題了~


參考:http://www.peterprovost.org/blog/2012/06/19/adding-ninject-to-web-api
Related Posts Plugin for WordPress, Blogger...