验证Ninject绑定

时间:2018-02-01 14:24:28

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

我有一个使用Ninject作为其DI的WebAPI项目。 我想验证/确认绑定已经全部工作,但我已经想到的代码有点气味了。所以我想知道是否有更好的方法。

来电者:

    private IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());
        GlobalConfiguration.Configuration.DependencyResolver = kernel.Get<System.Web.Http.Dependencies.IDependencyResolver>();

        try
        {
            RegisterServices(kernel);
            CheckServices(kernel);
            return kernel;
        }
        catch (ActivationException ex)
        {
            if (kernel != null)
                kernel.Dispose();

            log.Fatal(ex);
            throw;
        }
        catch
        {
            if (kernel != null)
                kernel.Dispose();
            throw;
        }
    }

然后:

    private void RegisterServices(StandardKernel kernel)
    {
        kernel.Bind<Func<IKernel>>().ToMethod(context => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

剪断以避免过多的代码警告!

    private void CheckServices(StandardKernel kernel)
    {
        ILog ilog = kernel.TryGetAndThrowOnInvalidBinding<ILog>();
        IDBHandler idbhandler = kernel.TryGetAndThrowOnInvalidBinding<IDBHandler>();
        IUserManagementService user = kernel.TryGetAndThrowOnInvalidBinding<IUserManagementService>();
        IMassService mass = kernel.TryGetAndThrowOnInvalidBinding<IMassService>();
        IPPSService pps = kernel.TryGetAndThrowOnInvalidBinding<IPPSService>();

        ilog = null;
        idbhandler = null;
        ambient = null;
        auth = null;

        pps = null;
        mass = null;
        user = null;

        log.Info("Ninject Kernel Bindings checked.");
    }

1 个答案:

答案 0 :(得分:1)

我不明白为什么你需要像在生产代码中那样检查绑定。如果绑定检查失败,您打算做什么?

相反,我会用单元测试检查它们。我使用以下方法,循环遍历模块中的每个绑定并尝试实例化它们:

[Test]
public void AllModuleBindingsTest()
{
    var kernel = new StandardKernel(new MyNinjectModule())
    foreach (var binding in new MyNinjectModule().Bindings)
    {
        var result = kernel.Get(binding.Service);
        Assert.NotNull(result, $"Could not get {binding.Service}");
    }
}