user825875
user825875

Reputation: 53

MVC project No parameterless constructor defined for this object

im getting this error. Im newbie on MVC . Can you help me please.I found somethings but i didnt understand what i will do. Sorry for my english. I have 4 projects in a solution .Admin .UI .Core .Data I have a problem with admin side. Im trying to LoginFilter in admin page. When i run the project the page forwarding to /Account/Login page but its giving this error.

Error Page:

No parameterless constructor defined for this object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 

[MissingMethodException: No parameterless constructor defined for this object.]
   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) +206
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
   System.Activator.CreateInstance(Type type) +11
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +55

[InvalidOperationException: An error occurred when trying to create a controller of type 'WebHaber.Admin.Controllers.AccountController'. Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +76
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +88
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +194
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1098.0

AccountController.cs

using WebHaber.Core.Infrastructure;
using WebHaber.Data.Model;

namespace WebHaber.Admin.Controllers
{
    public class AccountController : Controller
    {

        #region Kullanıcı
        private readonly IKullaniciRepository _kullaniciRepository;
        public AccountController(IKullaniciRepository kullaniciRepository)
        {
            _kullaniciRepository = kullaniciRepository;
        }
        #endregion

        // GET: Account
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(Kullanici kullanici)
        {
            var KullaniciVarmi = _kullaniciRepository.GetMany(x => x.Email == kullanici.Email && x.Sifre == kullanici.Sifre && x.Aktif == true).SingleOrDefault();
            if (KullaniciVarmi != null)
            {
                if (KullaniciVarmi.Rol.RolAdi == "Admin")
                {
                    Session["KullaniciEmail"] = KullaniciVarmi.Email;
                    return RedirectToAction("Index", "Home");
                }
                ViewBag.Mesaj = "Yetkisiz Kullanıcı";
                return View();
            }
            ViewBag.Mesaj = "Kullanıcı Bulunamadı";
            return View();
        }

LoginFilter.cs

namespace WebHaber.Admin.CustomFilter
{
      public class LoginFilter : FilterAttribute, IActionFilter
        {

            public void OnActionExecuted(ActionExecutedContext context)
            {
                HttpContextWrapper wrapper = new HttpContextWrapper(HttpContext.Current);
                var SessionControl = context.HttpContext.Session["KullaniciEmail"];
                if (SessionControl == null)
                {
                    context.Result = new RedirectToRouteResult(
                        new RouteValueDictionary { { "Controller", "Account" }, { "action", "Login" } });

                }

            }

            public void OnActionExecuting(ActionExecutingContext context)
            {}

BootStrapper.cs

using Autofac;
using Autofac.Integration.Mvc;
using WebHaber.Core.Infrastructure;
using WebHaber.Core.Repository;
using WebHaber.Data.DataContext;

namespace WebHaber.Admin.Class
{
    public class BootStrapper
        {
            //Boot aşamasında çalışacak.
            public static void RunConfig()
            {
                BuilAutoFac();
            }

            private static void BuilAutoFac()
            {
                var builder = new ContainerBuilder();

                builder.RegisterType<HaberRepository>().As<IHaberRepository>();

                builder.RegisterType<ResimRepository>().As<IResimRepository>();

                builder.RegisterType<KullaniciRepository>().As<IKullaniciRepository>();

                builder.RegisterType<RolRepository>().As<IRolRepository>();

                builder.RegisterControllers(typeof(MvcApplication).Assembly);

                var container = builder.Build();
                DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            }
        }

Global.asax

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BootStrapper.RunConfig();

        }
    }

KullaniciRepository.cs

namespace WebHaber.Core.Repository
{
   public class KullaniciRepository : IKullaniciRepository
    {
        private readonly HaberContext _context = new HaberContext();

        public IEnumerable<Kullanici> GetAll()
        {
            //Tüm haberler dönecek
            return _context.Kullanici.Select(x => x);
        }

        public Kullanici GetByID(int id)
        {
            return _context.Kullanici.FirstOrDefault(x => x.ID == id);
        }

        public Kullanici Get(Expression<Func<Kullanici, bool>> expression)
        {
            return _context.Kullanici.FirstOrDefault(expression);
        }

        public IQueryable<Kullanici> GetMany(Expression<Func<Kullanici, bool>> expression)
        {
            return _context.Kullanici.Where(expression);
        }

        public void Insert(Kullanici obj)
        {
            _context.Kullanici.Add(obj);
        }


        public void Update(Kullanici obj)
        {
            _context.Kullanici.AddOrUpdate();
        }

        public void Delete(int id)
        {
            var kullanici = GetByID(id);
            if (kullanici!= null)
            {
                _context.Kullanici.Remove(kullanici);
            }

        }

        public int Count()
        {
            return _context.Kullanici.Count();
        }
        public void Save()
        {
            _context.SaveChanges();
        }
    }
}

IKullaniciRepository.cs

namespace WebHaber.Core.Infrastructure
{
    public interface IKullaniciRepository : IRepository<Kullanici>
    {
    }
}

IRepository.cs

namespace WebHaber.Core.Infrastructure
{
    public interface IRepository<T> where T: class
    {
        IEnumerable<T> GetAll();

        T GetByID(int id);

        T Get(Expression<Func<T, bool>> expression);

        IQueryable<T> GetMany(Expression<Func<T, bool>> expression);

        void Insert(T obj);

        void Update(T obj);

        void Delete(int id);

        int Count();

        void Save();

    }

}

Kullanici.cs model

namespace WebHaber.Data.Model
{
    [Table("Kullanici")]
    public class Kullanici
    {
        public int ID { get; set; }

        [Display(Name = "Ad Soyad")]
        [MaxLength(150, ErrorMessage = "150 karakterden fazla girildi.")]
        [Required]
        public string AdSoyad { get; set; }

        [Display(Name = "Email")]
        [DataType(DataType.EmailAddress)]
        [Required]
        public string Email { get; set; }

        public string KullaniciAdi { get; set; }

        [Display(Name = "Şifre")]
        [DataType(DataType.Password)]
        [Required]
        public string Sifre { get; set; }
..............
..............
.............

Upvotes: 2

Views: 4378

Answers (2)

user825875
user825875

Reputation: 53

@Zephyr thank you for help. I added new global.asax file. Because my Application_Start() was not firing.

In global.asax Old one :

 public class MvcApplication : System.Web.HttpApplication

new one: `

public class Global : System.Web.HttpApplication`

Upvotes: 0

Zephyr
Zephyr

Reputation: 313

The issue is pretty straightforward — An error occurred when trying to create a controller of type 'WebHaber.Admin.Controllers.AccountController'. Make sure that the controller has a parameterless public constructor.

You're trying to use Autofac to inject IKullaniciRepository service into the AccountController but the compiler couldn't find one although you've the declared the service registration at BootStrapper.cs

Therefore it's likely that BootStrapper.cs's RunConfig never get invoked. Just place a call (e.g. BootStrapper.RunConfig()) to Application_Start() method in Global.asax and you're fine.

Upvotes: 3

Related Questions