No parameterless constructor was defined for this object

1

I'm building an ASP.NET MVC5 application using DDD and I've separated my IoC layer from my web application. In my controllers I have parameterized constructors to receive an instance of my class of services. I am using Ninject, in this 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 bind to my dependencies.

The problem is that when I call my action, for example Clientes/Index , the system returns 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 move to DependencyResolver for my dependency injection.

I already implemented in another project using NinjectWebCommon, however, this was within the Asp.Net MVC project. What I want is to implement this on an outside project.

How do I do this?

    
asked by anonymous 22.01.2015 / 19:49

2 answers

2

Solution

As @iuristona had said, the problem was that my IoC container was not able to resolve the dependency of the builder on my Controller.

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

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 had not put typeof in my generic dependencies as IServiceBase and IRepositoryBase . If you do not do this the compiler can not find the type of the generic classes and consequently the IoC container can not resolve the dependency. After adding typeof I did the following:

IoC Class

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

MyDependencyResolver class

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 call of the SetResolver of the DependencyResolver for my MyDependencyResolver class that is in a separate project. So I was able to isolate my Dependency Injection layer in an infrastructure project separate 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());
}
    
23.01.2015 / 10:54
1

Well, this error occurs because your IoC container is not being able to resolve the dependency in the constructor of your Controller , whereas the MVC does not find a version of the constructor without parameters.

I do not know if you will be able to implement your IoC pro MVC in an external project, since you need to implement the IDependencyResolver interface that is part of 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");
        }
    }
    
22.01.2015 / 20:14