Ninject does not load dependencies. Asp.NET MVC C #

3

I'm using NinjectWebCommom to work with Inject. I installed the package via Nuget and automatically it creates a class named "NinjectWebCommon" in the App_Start folder, as the documentation itself says. I need to know why it is not working correctly, here are some code snippets:

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>();
    }
}

Controller

public class FooController : Controller
{
    private readonly IFooService fooService;

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

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

This excerpt generates the following error

  

Error activating IFooService No matching bindings are available, and   the type is not self-bindable. Activation path:

     

2) Injection of dependency IFooService into parameter fooService of   constructor of type FooController

     

1) Request for FooController

     

Suggestions:

     

1) Ensure that you have defined a binding for IFooService.   2) If the binding was defined in a module, ensure that the module has   been loaded into the kernel.

     

3) Ensure you have not accidentally created more than one kernel.

     

4) If you are using constructor arguments, ensure that the parameter   name matches the constructors parameter name.   5) If you are using automatic module loading, ensure the search path   and filters are correct.

Use IoC to resolve instances, but it works only in my HomeController, if I change to another controller using EXACTLY the same code (with the IoC), it generates the error again. Follows the code using the IoC.

Follow the snippet using IoC:

private readonly IFooService fooService;

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

public ActionResult Index()
{
    ViewBag.MyFoos = this.fooService.All();

    return View();
}

generates this error

No matching bindings are available, and the type is not self-bindable.

Error activating IFooService No matching bindings are available, and the type is not self-bindable.

  

Activation path:   1) Request for IFooService

     

Suggestions:

     

1) Ensure that you have defined a binding for IFooService.

     

2) If the binding was defined in a module, ensure that the module has   been loaded into the kernel.

     

3) Ensure you have not accidentally created more than one kernel.

     

4) If you are using constructor arguments, ensure that the parameter   name matches the constructors parameter name.

     

5) If you are using automatic module loading, ensure the search path   and filters are correct.

    
asked by anonymous 31.07.2015 / 04:03

1 answer

1

I solved the problem by loading all "NinjectModule" from my application's hierarchy.

I thought it was enough to only load the main module, so I created another static method inside the "NinjectWebCommon" just to separate the responsibilities and organize the code. Here is the code used:

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

where I load all the respective Repositories, Services, and Validators in Kernel Creation.

 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;
                }
            });
        }

method created by me inside NinjectWebCommon as mentioned above, only to register the required dependencies.

This whole code is basically native and comes embedded within the Nugget Ninject.MVC4 package (installed via Console Package Manager inside Visual Studio). This package inserts a class in the App_Start directory called "NinjectWebCommon", and is the one that made these changes.

The controler is set to send the package documentation as follows:

public class HomeController : Controller
        {
            private readonly IFooService fooService;

            public HomeController(IFooService fooService)
            {
                this.fooService = fooService; //Daqui para frente é possível usar normalmente o service.
            }
        }
    
31.07.2015 / 18:44