12

I have searched long and hard but found nothing that helped yet. Where am I going wrong? I really do not know what to do. I wrote all the details below. I've tried and did not succeed.

An error occurred when trying to create a controller of type 'TypeNewsController'. Make sure that the controller has a parameterless public constructor.

 public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            Bootstrapper.Run();
        }
    }

my apicontroller :

public class TypeNewsController : ApiController
    {
        private readonly ITypeNewsService _typeNewsService;

        public TypeNewsController(ITypeNewsService typeNewsService)
        {
            _typeNewsService = typeNewsService;
        }
        [HttpGet]
        public TypeNewsResponse Get([ModelBinder] PageRequest model)
        {
            model = model ?? new PageRequest();
            var output = _typeNewsService.GetTypeNewss().ToList();
            return new TypeNewsResponse
            {
                Page = model.PageIndex,
                Records = model.PageSize,
                Rows = output.ToList(),
                Total = output.Count() / model.PageSize,
            };
        }
    }

error :

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
An error occurred when trying to create a controller of type 'TypeNewsController'. Make sure that the controller has a parameterless public constructor.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()
</StackTrace>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'JuventusNewsSiteApk.Controllers.TypeNewsController' does not have a default constructor
</ExceptionMessage>
<ExceptionType>System.ArgumentException</ExceptionType>
<StackTrace>
at System.Linq.Expressions.Expression.New(Type type) at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
</StackTrace>
</InnerException>
</Error>

Bootstrapper class :

public static class Bootstrapper
    {
        public static void Run()
        {
            SetAutofacContainer();
            //Configure AutoMapper
            AutoMapperConfiguration.Configure();
        }

        private static void SetAutofacContainer()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
            builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerRequest();
            builder.RegisterAssemblyTypes(typeof(NewsRepository).Assembly)
                .Where(t => t.Name.EndsWith("Repository"))
                .AsImplementedInterfaces().InstancePerRequest();
            builder.RegisterAssemblyTypes(typeof(NewsService).Assembly)
                .Where(t => t.Name.EndsWith("Service"))
                .AsImplementedInterfaces().InstancePerRequest();

            builder.RegisterAssemblyTypes(typeof(DefaultFormsAuthentication).Assembly)
                .Where(t => t.Name.EndsWith("Authentication"))
                .AsImplementedInterfaces().InstancePerRequest();

            builder.Register(
                c => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new JuventusNewsApkEntities())))
                .As<UserManager<ApplicationUser>>().InstancePerRequest();

            builder.RegisterFilterProvider();
            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }

update :

 public class TypeNewsService : ITypeNewsService
    {
        private readonly ITypeNewsRepository _typeNewsRepository;
        private readonly IUnitOfWork _unitOfWork;
        public TypeNewsService(ITypeNewsRepository typeNewsRepository,
            IUnitOfWork unitOfWork)
        {
            _typeNewsRepository = typeNewsRepository;
            _unitOfWork = unitOfWork;
        }

        #region ITypeNewsService Member

        public void AddTypeNews(TypeNews typeNews)
        {
            _typeNewsRepository.Add(typeNews);
            SaveTypeNews();
        }

        public void DeleteTypeNews(int id)
        {
            _typeNewsRepository.DeleteById(id);
            SaveTypeNews();
        }

        public IEnumerable<TypeNews> GetTypeNewss()
        {
            var output = _typeNewsRepository.GetAll();
            return output;
        }

        public void SaveTypeNews()
        {
            _unitOfWork.Commit();
        }

        #endregion

    }

    public interface ITypeNewsService
    {
        void AddTypeNews(TypeNews typeNews);
        void DeleteTypeNews(int id);
        IEnumerable<TypeNews> GetTypeNewss();
        void SaveTypeNews();
    }
Alex Peck
  • 4,467
  • 1
  • 29
  • 36
Football-Is-My-Life
  • 1,287
  • 6
  • 17
  • 32

4 Answers4

19

Your controller is WebApi controller and registration for Autofac differs from MVC registration. WebApi does not use DependencyResolver, so you'll need to tell WebApi to use Autofac resolver specifically.

You'll need to add this to your SetAutofacContainer code:

// Create the depenedency resolver.
var resolver = new AutofacWebApiDependencyResolver(container);

// Configure Web API with the dependency resolver.
GlobalConfiguration.Configuration.DependencyResolver = resolver;

See https://code.google.com/p/autofac/wiki/WebApiIntegration for more info.

trailmax
  • 31,605
  • 20
  • 126
  • 225
11

In my case, the reason was that the resolver could not find a mapping. That is, suppose say HomeController has a dependency on IDumb, the resolver could not find a concrete implementation of Dumb which implements IDumb.

In other words the error message

**No parameterless constructor defined for this object
An error occurred when trying to create a controller of type 'ToDoListT1.WebApp.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor**

is completely misleading.

In my case I just resolved by adding a reference to the project of the class Dumb. It should have been something like "No mapping for IDumb could be found.". I am not sure whether the problem is with NInject or MS. Whatever, it took me hours to find this out.

starsplusplus
  • 1,154
  • 3
  • 17
  • 31
VivekDev
  • 7,143
  • 11
  • 58
  • 107
  • I've been having the same problem, and I have some unimplemented interfaces, so this looks like it will fix it. Thanks! +1! – starsplusplus Nov 06 '14 at 14:31
  • It looks like Web API will show this error if the constructor for an ApiController throws an exception, no matter what it is. I also had a problem with Ninject, but you can see the same behavior if you just add `throw new Exception("sadface");` to the constructor. – Nick Jan 27 '16 at 15:50
0

Make you sure than you're calling the same call type, I mean, Get, Post, Put, and what kind you have in the controller method.

And do you need to add your valid repository to NijectConfig.cs for the controller.

kernel.Bind<[iRepo]>().To<[Repo]>().InRequestScope();

David Castro
  • 1,197
  • 13
  • 14
-5

For controller you should have parameter less constructor. If you want to use parametrized constructor please use code like below.

Pass object of TypeNewsService class

private readonly ITypeNewsService _typeNewsService;
public TypeNewsController():this(new TypeNewsService ())
{
} 
public TypeNewsController(ITypeNewsService typeNewsService)
{
   _typeNewsService = typeNewsService;
}
Sujit Patil
  • 165
  • 4
  • The poster has asked how to 'Inject' an instance into a parameterized constructor. Please read about Dependency Injection. If he had wanted to create a new instance using the the 'new' keyword, he wouldn't need to pass it from the the default constructor to a parameterized constructor in the same class. – Syed Waqas Feb 25 '17 at 06:25