c# - Ninject 在具有多个程序集的 WebApi 项目中抛出激活异常

标签 c# asp.net-web-api ninject ninject-extensions ninject.web

我的 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");
    }        
}

异常(exception)是

[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,包括包含 IHostBufferPolicySelector 类型的 System.Web.Http.dll。

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

最佳答案

根据 Remo 的回答提示和 Filip 的评论以及大量的调试时间,我发现使用 this.resolver.Get(serviceType) 而不是 GetService() 实现中的 this.resolver.TryGet(serviceType) 是我遇到的问题的罪魁祸首。

我计划写一篇关于此的详细博客文章,但简而言之,一旦我们使用以下行将 NinjectDependencyResolver 插入 MVC 中: GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel); 并且我们没有定义框架级依赖项绑定(bind)(例如 IHostBufferPolicySelector 等),Get() 方法会针对某些框架级依赖项引发异常通过 Ninject 解决。使用 TryGet() 不会引发异常,并且框架会回退到默认依赖项以解决 Unresolved (也称为 null)依赖项,例如 IHostBufferPolicySelector。所以,选项是

  1. 使用 TryGet() 方法解决依赖关系。
  2. 将 Get 包裹在 Try/Catch 中并丢弃异常。

关于c# - Ninject 在具有多个程序集的 WebApi 项目中抛出激活异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13347220/

相关文章:

c# - 使用通过 HTTPS 传输的 system.net.socket 检查接收到的数据

c# - 为什么初始化程序不能处理返回列表 <t> 的属性?

asp.net-web-api - 如何配置 OData 不处理 Web Api 中的非 odata 异常

c# - 如何在 C# 中定义带有抽象参数的 REST 方法

c# - 使用 Ninject 和 Ninject.Extensions.Nlog2 的空引用异常

c# - 在两个服务中使用 ninject 都会在 C# 中创建循环依赖

c# - Select * from TableName 的 Lambda 表达式

c# - Restsharp 引用中的版本问题

c# - ASP.NET WebAPI Ajax 取得进展

c# - 如何在 Ninject 中使用 Provider