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

Asked

Viewed 502 times

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’s not working properly, follow 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 section 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 stretch 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.

  • What are the dependencies of FooService? They’re being injected as well?

  • And up there in Ninjectwebcommon.Cs, has the web Activator? looks like this: [assembly: WebActivatorEx.PreApplicationStartMethod...]

  • Try to replace private readonly Ifooservice fooService; for public Ifooservice Fooservice {get; set;} and remove the constructor parameter from the Foocontroller class. The line fooService = fooService is not required as Ninject itself will initialize the Property with dependency injection.

  • @Ulyssesalves made the modifications and did not work. get; set; leaves the null interface.

  • And that mistake Error Activating Ifooservice No matching bindings are available, and the type is not self-bindable. still occurs after this change?

  • @Ulyssesalves no, but with service null, the problem remains...

  • The code you used with comments in English you took from some article? If yes, could you give us the link so we can analyze better?

  • @Ulyssesalves is part of Nuget, it automatically installs this class inside the project, follows the link of the documentation: https://github.com/ninject/Ninject.Web.Mvc/wiki/Setting-up-an-MVC3-application

  • @brazilianldsjaguar yes for the second question, the first I do not know answer you for sure, but I believe that from the used class, he should solve the others and he has.

  • @Luiznegrini So, you inherited your Mvcapplication class from Ninjecthttpapplication, as shown on the page? public class Mvcapplication : Ninjecthttpapplication

  • 1
Show 6 more comments

1 answer

1

I solved the problem by loading all "Ninjectmodule" of my application hierarchy.

I thought it was enough to just load the main module, so I created another static method within "Ninjectwebcommon" just to separate the responsibilities and organize the code. Below is the code used:

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

where I upload all the respective Repositories, Services and Validators when creating the Kernel.

 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 within Ninjectwebcommon as mentioned above, only to register the required dependencies.

All this code is basically native and comes inside the Nuget Ninject.MVC4 package (installed via Console Package Manager within Visual Studio). This package inserts a class in the App_start directory called "Ninjectwebcommon", and is the one that made these changes.

the controller is defined as 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.
            }
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.