Ninject依赖注入仅适用于一个控制器

时间:2017-10-06 00:23:52

标签: asp.net dependency-injection asp.net-web-api2 ninject

我最初使用ninject为DI.net web api 2服务设置DI,只需一个控制器,一切正常。添加第二个控制器后,ninject不适用于新控制器。我收到以下错误:

“尝试创建'VstsController'类型的控制器时发生错误。确保控制器具有无参数的公共构造函数。”

第一个控制器(ninject的工作原理):

public class RepositoryController : ApiController
{
    private GitHubClient _client;

    public RepositoryController(IGitHubClientAuthenticated gitHubClientAuthenticated)
    {
        _client = gitHubClientAuthenticated.Client;
        _client.Credentials = gitHubClientAuthenticated.Credentials;
    }

第二控制器:

    public class VstsController : ApiController
{
    private VssConnection _connection;
    public VstsController(IVssConnectionAuthenticated vssConnectionAuthenticated)
    {
        _connection = vssConnectionAuthenticated.VssConnection;
    }

Ninject配置文件:

private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<IVssConnectionAuthenticated>().To<VssConnectionAuthenticated>();
        kernel.Bind<IGitHubClientAuthenticated>().To<GitHubClientAuthenticated>();
        kernel.Bind<IAuthenticationHelper>().To<AuthenticationHelper>();

    }    

如果我想继续添加控制器,是否需要调整任何内容?找不到任何关于此的文档。提前致谢

编辑:包括ninject设置代码以及VssAuthenticated + IvssAuthenticated:

namespace Dashboard.WebAPI.Models
{
public interface IVssConnectionAuthenticated
    {
    VssConnection VssConnection { get;  }
    Uri Uri { get; }
    }
}


namespace Dashboard.WebAPI.Models
{
public class VssConnectionAuthenticated: IVssConnectionAuthenticated
{
    public VssConnection VssConnection { get; private set; }
    public Uri Uri { get; private set; }

    VssConnectionAuthenticated()
    {
        Uri = new Uri("uri");
        string vstsSecretUri = "vstssecreturi";
        GetKeyVaultSecret keyVaultSecretGetter = new GetKeyVaultSecret(new AuthenticationHelper(), vstsSecretUri);
        string keyVaultSecret = keyVaultSecretGetter.KeyVaultSecret;
        VssBasicCredential vssBasicCredential = new VssBasicCredential(string.Empty, keyVaultSecret); 
        VssConnection = new VssConnection(Uri, vssBasicCredential);
    }

完整Ninject配置文件:

namespace Dashboard.WebAPI.App_Start
{
using System;
using System.Web;

using Microsoft.Web.Infrastructure.DynamicModuleHelper;

using Ninject;
using Ninject.Web.Common;
using System.Web.Http;
using Dashboard.WebAPI.Models;

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 the application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            RegisterServices(kernel);
            GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
            return kernel;
        }
        catch
        {
            kernel.Dispose();
            throw;
        }
    }

    /// <summary>
    /// Load modules and register services 
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<IVssConnectionAuthenticated>().To<VssConnectionAuthenticated>();
        kernel.Bind<IGitHubClientAuthenticated>().To<GitHubClientAuthenticated>();
        kernel.Bind<IAuthenticationHelper>().To<AuthenticationHelper>();

    }        
}

}

将Ninject注册为依赖性解析器:

namespace Dashboard.WebAPI.App_Start
{
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;
    }
}
public class NinjectDependencyResolver: NinjectDependencyScope, IDependencyResolver
{
    IKernel kernel;

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

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

}

1 个答案:

答案 0 :(得分:1)

如果其他人遇到此问题 - 问题出在VssConnectionAuthenticated:构造函数需要公开。