Injection of Depension with Ninject C#

Asked

Viewed 1,071 times

1

I am developing an application that has 4 layers Dominio, Infra, Servico e Web When I have access to a route for example Home/Index he says that there is no constructor without parameters, my constructor is like this :

public HomeController(IPessoaServico pessoaServico)
{
    this.pessoaServico = pessoaServico;
}

I have a class NinjectWebCommon.cs in the briefcase App_Start with the following code.

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Web.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(Web.App_Start.NinjectWebCommon), "Stop")]

namespace Web.App_Start
{
    using System;
    using System.Web;
    using Microsoft.Web.Infrastructure.DynamicModuleHelper;
    using Ninject;
    using Ninject.Web.Common;
    using Infra.Banco.Interface;
    using Infra.Banco;
    using Infra.Repositorio.Interface;
    using Infra.Repositorio;
    using Servico.Interface;
    using Servico;

    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>

        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<IDataBaseFactory>().To<DataBaseFactory>().InRequestScope();
            kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();

            kernel.Bind<IPessoaRepositorio>().To<PessoaRepositorio>();
            kernel.Bind<IPessoaServico>().To<PessoaServico>();
    }
}

I put just one of the entities for example, this is the first time I’m doing an application like this and I think I’m missing something, in case someone can help me, if you need more information and just talk.

EDIT : I searched a little and saw some people indicating the installation of 2 additional packages Ninject MVC 5 and Ninject WEB.API , I’m adding the 2 to do tests.

  • in that code does not have the IPessoaServico recorded in the method RegisterServices?

  • Yes, there are all the entities , I put only the first example. but the rest of the entities are registered in the same way including Personal

  • To avoid confusion the code has to match the other code, avoid the people find what I found, I will elaborate a test, which is the version of your application ASP.NET ?

  • MVC version = 5.2.3.0 am using Visual Studio 2015

  • Microsoft.AspNet.Webapi. 5.2.3

  • Are you making injection into Webapi and also Web? You need it to work in both?

  • In the future I will make the Web api , but now it is only web itself, I have not added the web api package only the MVC5

Show 3 more comments

1 answer

1


So that dependency injection with Ninject work so much to Web MVC and Webapi requires the installation of two packages:

Install-Package Ninject.MVC5-Version 3.2.0

and

Install-Package Ninject.WebApi.Dependencyresolver

after installing these two packages enter the folder App_Start in the archive NinjectWebCommon.cs and add a line:

System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);

in the method CreateKernel() as example layout just below:

private static IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    try
    {
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
        System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = 
           new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);

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

a detail is also in the Global.asax put on your first line GlobalConfiguration.Configure(WebApiConfig.Register):

protected void Application_Start()
{
     GlobalConfiguration.Configure(WebApiConfig.Register);
     ...
  • 1

    It worked perfectly, thank you very much for your help, I was long trying to solve this problem, thank you very much.

  • Yes, I understand, you have to see possibilities and study in this case if you’re not going to compromise performance too much. Maybe doing a project for each and putting separate projects will give more work in the maintenance and coding part. Have to analyze even if it’s little thing Webapi I would put it all together...

  • 1

    Thank you so much you helped me so much, thanks so much.

Browser other questions tagged

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