5

我的 asp.net WebApi 项目由服务、核心和数据访问的多个程序集组成。为了在项目中使用 Ninject 作为我的 DI 容器,我从 NuGet 添加了 Ninject.Web.Common 包。然后,我将 IDependencyResolver 实现为:

public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
    readonly IKernel kernel;

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

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

public class NinjectDependencyScope : IDependencyScope
{
    IResolutionRoot resolver;

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

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

        var resolved = this.resolver.Get(serviceType);
        return resolved;
    }

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

        return this.resolver.GetAll(serviceType);
    }

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

        resolver = null;
    }
}

这是我的 Ninject.Web.Common.cs。

public static class NinjectWebCommon 
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start() 
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
        RegisterServices(kernel);

        GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
        return kernel;
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind(x =>
            x.FromAssembliesInPath(AppDomain.CurrentDomain.RelativeSearchPath)
            .SelectAllIncludingAbstractClasses()
            .BindDefaultInterface()
            .Configure(config => config.InSingletonScope()));

        //kernel.Bind(x => 
        //    {
        //        x.FromAssembliesMatching("*")
        //        .SelectAllClasses()
        //        .BindDefaultInterface()
        //        .Configure(b => b.InTransientScope());
        //    });
        //kernel.Load()
        //kernel.Bind<ISecurityService>().To<SecurityServiceImplementation>();

        //kernel.Bind(x => x
        //    .FromAssembliesMatching("*")
        //    .SelectAllClasses()
        //    .BindDefaultInterface());
        //.Configure(b => b.InTransientScope()));
        //kernel.Load("*.dll");
    }        
}

例外是

[ActivationException: Error activating IHostBufferPolicySelector
No matching bindings are available, and the type is not self-bindable.
Activation path:
1) Request for IHostBufferPolicySelector

我使用了各种注册(注释掉),但没有一个工作。NinjectWebCommon.cs -> CreateKernel() 方法中的断点被命中,GetService(System.Type serviceType) 方法中的断点也是如此。AppDomain.CurrentDomain.RelativeSearchPath 解析到应用程序的 bin 目录,它包含所有 dll,包括 System.Web.Http.dll,其中包含 IHostBufferPolicySelector 类型。

如何正确使用 Ninject.Extensions.Conventions 设置内核以进行类型解析?

4

3 回答 3

6

从 Remo 的答案中的提示和 Filip 的评论以及大量的调试时间,我发现在 GetService() 实现中使用this.resolver.Get(serviceType)而不是this.resolver.TryGet(serviceType)在我的情况下是罪魁祸首。

我计划写一篇关于此的详细博客文章,但简短的是,一旦我们使用以下行将 NinjectDependencyResolver 插入 MVC: GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel); 并且我们没有定义框架级别的依赖绑定(例如 IHostBufferPolicySelector 等),就会引发异常一些Get()框架级别依赖项的方法,当它们没有通过 Ninject 解决时。Using不会引发异常,并且框架会退回到未解决的(又名 null)依赖项的默认依赖项,例如 IHostBufferPolicySelector。所以,选项是TryGet()

  1. 使用 TryGet() 方法来解决依赖关系。
  2. 在 Try/Catch 中包装 Get 并丢弃异常。
于 2012-11-14T17:17:58.403 回答
2

试试这个帖子。不要捕获 Ninject 异常,而是捕获所有 WebApi 调用的异常。http://blog.greatrexpectations.com/2013/05/15/exception-handling-for-web-api-controller-constructors/ 在堆栈跟踪中,发生异常的构造函数是可见的。

于 2013-08-09T14:15:38.437 回答
1

没有类HostBufferPolicySelector,所以没有类IHostBufferPolicySelector是默认接口。你可以试试BindAllInterfacesBindDefaultInterfaces

于 2012-11-12T16:30:25.590 回答