【问题标题】:Ninject does not load dependencies using Asp.NET MVC 4 C#Ninject 不使用 Asp.NET MVC 4 C# 加载依赖项
【发布时间】:2015-07-30 20:51:01
【问题描述】:

我正在使用 NinjectWebCommon 在我的控制器中执行注入。我通过 Nuget 安装了这个包,他在我的 App_Start 中创建了 NinjectWebCommon.cs,正如它在自己的文档中所说的那样。我需要知道为什么它不能正常工作,因为我一步一步地遵循文档。遵循一些sn-ps:

NinjectWebCommon.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();

            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

                RegisterServices(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            //kernel.Load(AppDomain.CurrentDomain.GetAssemblies());
            kernel.Bind<IFooService>().To<FooService>();
        }
    }

控制器:

public class FooController : Controller
    {
        private readonly IFooService fooService;

        public FooController(IFooService fooService)
        {
            this.fooService = fooService;
        }

        public ActionResult Index()
        {
            return View(this.fooService.All());
        }
    }

这会产生这个错误:

错误激活 IFooService 没有匹配的绑定可用,并且 该类型不可自绑定。激活路径:
2) 注入 将 IFooService 依赖到构造函数的参数 fooService 中 类型 FooController
1) 请求 FooController

建议:
1)确保您已经定义了一个绑定 IFooService.
2) 如果绑定是在模块中定义的,请确保 该模块已加载到内核中。
3) 确保您没有 意外创建了多个内核。
4)如果您正在使用 构造函数参数,确保参数名称与 构造函数参数名称。
5)如果您使用的是自动模块 加载中,确保搜索路径和过滤器正确。

使用 IoC 来解析实例,但它仅适用于我的 HomeController,如果我使用完全相同的代码(使用 IoC)更改为另一个控制器,它会再次生成错误。遵循使用 IoC 的代码。

使用 IoC:

private readonly IFooService fooService;

        public HomeController()
        {
            this.fooService = IoC.Instance.Resolve<IFooService>();
        }

        public ActionResult Index()
        {

            ViewBag.MyFoos = this.fooService.All();

            return View();
        }

产生这个错误:

没有匹配的绑定可用,并且类型不是自绑定的。

激活 IFooService 时出错 没有匹配的绑定可用, 并且类型不能自绑定。

激活路径:
1) 请求 IFooService

建议:

1) 确保 您已经为 IFooService 定义了一个绑定。
2)如果绑定 在模块中定义,确保模块已加载到 内核。
3) 确保您没有意外创建多个 核心。 4) 如果您使用构造函数参数,请确保 参数名称与构造函数参数名称匹配。 5)如果你是 使用自动模块加载,确保搜索路径和过滤器是 正确。

【问题讨论】:

    标签: c# dependency-injection ninject


    【解决方案1】:

    您确定您有ISetorService 的绑定吗?我在您发布的代码中没有看到。

    【讨论】:

    • 对不起,这是绑定: private static void RegisterServices(IKernel kernel) { //kernel.Load(AppDomain.CurrentDomain.GetAssemblies()); kernel.Bind().To(); }
    • 这是IFooService的绑定,但错误是在寻找ISetorService
    • 不,我只是忘记更改“foo”的错误... = /
    【解决方案2】:

    我通过加载我的应用程序层次结构的所有“NinjectModule”解决了这个问题。

    我认为只加载主模块就足够了,然后在“NinjectWebCommon”中创建了另一个静态方法,只是为了分离职责和组织代码。下面是使用的代码:

    var kernel = new StandardKernel(new Repository(), new Service(), new ValidationAndBusinessRules());
    

    在创建内核时携带所有存储库、服务和验证器。

    private static void RegisterObrigatoryServices(IKernel kernel)
            {
                kernel.Bind<IIdentityProvider>().To<ServiceIdentityProvider>();
                kernel.Bind<Guid>().ToMethod(ctx => default(Guid)).Named("CurrentProcessId");
                kernel.Bind<ISession>().ToMethod(ctx =>
                {
                    SessionPoolManager.Update();
    
                    Guid processId = kernel.Get<Guid>("CurrentProcessId", new Parameter[] { });
    
                    if (processId == default(Guid))
                    {
                        return SessionFactoryBuilder.SessionFactory(kernel.Get<IIdentityProvider>()).OpenSession();
                    }
                    else
                    {
                        ISession session = SessionPoolManager.Get(processId);
                        if (session == null)
                        {
                            session = SessionFactoryBuilder.SessionFactory(kernel.Get<IIdentityProvider>()).OpenSession();
                            SessionPoolManager.Register(processId, session);
                        }
    
                        return session;
                    }
                });
            }
    

    我在上面提到的 NinjectWebCommon 中创建的方法,只是为了记录所需的依赖关系。

    所有这些代码基本上都是原生的,并已插入到 Nuget Ninject.MVC4 包中(通过 Visual Studio 中的包管理器控制台安装)。这个包在 App_Start 目录中插入了一个名为“NinjectWebCommon”的类,正是我进行了这些更改。

    控制器设置发送包文档,如下:

    public class HomeController : Controller
            {
                private readonly IFooService fooService;
    
                public HomeController(IFooService fooService)
                {
                    this.fooService = fooService; //Daqui para frente é possível usar normalmente o service.
                }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多