No constructor without parameters has been defined for this object

Asked

Viewed 8,286 times

1

I am building an ASP.NET MVC5 application using DDD and have separated my Ioc layer from my web application. In my controllers I have constructs with parameter to receive an instance of my service class. I’m using Ninject, in which I created a class that extends Idependencyresolver, so in my Global.asax I can call the following code:

DependencyResolver.SetResolver(new App.Infra.Ioc.MyDependencyResolver());

Within the Mydependencyresolver class I make the Binds of my dependencies.

The problem is that when I call my action, for example Clientes/Index the system returns me the error:

Nenhum construtor sem parâmetros foi definido para este objeto.
[MissingMethodException: Nenhum construtor sem parâmetros foi definido para este objeto.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
   System.Activator.CreateInstance(Type type) +66
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +110

I know this error occurs because my dependency is not being mapped, but it should work, because in Global.asax I pass to Dependencyresolver my dependency injection.

I have already implemented in another project using Ninjectwebcommon, but this was within the Asp.Net MVC project. What I want is to implement this into an outside project.

How do I do that?

  • It would be interesting to put your Controller code in the question (Constructor, Action ...).

  • In fact, the error says that you are trying to create a class (which we don’t know) using an empty constructor. If the class is yours, implementing an empty constructor already solves this specific error.

  • Ever thought about putting a constructor method without parameters in the class? public IoC(){}

2 answers

2


Solution

As @iuristona had said, the problem was that my Ioc container was failing to resolve the dependency on my Controller’s constructor.

Investigating I discovered the problem, follow the code of the module Ninject:

public class ModuloDomainCommon : NinjectModule
    {
        public override void Load()
        {
            Bind(typeof(IServiceBase<>)).To(typeof(ServiceBase<>));
            Bind<ILoginService>().To<LoginService>();

            Bind(typeof(IRepositoryBase<>)).To(typeof(RepositoryBase<>));
            Bind<ILoginRepository>().To<LoginRepository>();

        }
    }

It occurred that I hadn’t put the typeof in my generic dependencies as IServiceBase and IRepositoryBase. If you don’t do this the compiler can’t find the generic class type and consequently the Ioc container can’t solve the dependency. After adding the typeof I did the following:

Ioc class

This is where I read the Ninject modules.

public class IoC
    {
        public IoC()
        {
            Kernel = new StandardKernel(
                new ModuloDomainCommon();

            ServiceLocator.SetLocatorProvider(() => new NinjectServiceLocator(Kernel));
        }

        public IKernel Kernel { get; private set; }
    }

Class Mydependencyresolver

Here is my class that extends the Idependencyresolver, and where I call the Ioc class that contains the Ninject modules.

public class MyDependencyResolver : IDependencyResolver
    {
        private readonly IKernel _kernel;
        public MyDependencyResolver()
        {
            var ioc = new IoC();
            _kernel = ioc.Kernel;
        }

    #region IDependencyResolver Members
        public object GetService(Type serviceType)
        {
            return _kernel.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return _kernel.GetAll(serviceType);
        }
    #endregion
}

Global.asax

Here is the Dependencyresolver Setresolver call for my Mydependencyresolver class that is in a separate project. So I was able to isolate my dependency injection layer in a separate infrastructure project from my presentation layer.

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            DependencyResolver.SetResolver(new MyApp.Infraestrutura.IoC.MyDependencyResolver());
}

1

Yeah, this error occurs because your Ioc container is failing to resolve the dependency on your constructor Controller, while MVC cannot find a constructor version without parameters.

I don’t know if you’ll be able to implement your Ioc pro MVC in an external project, as you need to implement the interface IDependencyResolver that is part of the System.Web.Mvc.

Follow my version using ninject "pure":

public class NinjectDependencyResolver : IDependencyResolver
    {
        private IKernel _kernel;

        public NinjectDependencyResolver()
        {
            _kernel = new StandardKernel();

            RegisterServices(_kernel);
        }

        public NinjectDependencyResolver(IKernel kernel)
        {
            _kernel = kernel;
        }

        public object GetService(Type serviceType)
        {
            return _kernel.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return _kernel.GetAll(serviceType);
        }

        public static void RegisterServices(IKernel kernel)
        {    

            // configure aqui seus serviços
            // kernel.Bind<InterfaceType>().To<ConcreteType>();
            kernel.Bind<DbContext>().To<MyDbContext>();//.WithConstructorArgument("nameOrConnectionString", "CpsConnectionString");
        }
    }
  • can find it. Your answer helped me, because that’s when I remembered that eror was occurring because I wasn’t able to solve the addiction. I posted the complete solution in the answer below.

Browser other questions tagged

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