MVC项目没有为此对象定义的无参数构造函数

时间:2017-04-21 01:02:35

标签: asp.net-mvc dependency-injection interface asp.net-mvc-5 autofac

我得到这个错误。我在MVC的新手。 你能帮帮我吗。我找到了一些东西,但我不明白我会做什么。对不起我的英语不好。 我在一个解决方案中有4个项目 .Admin .UI 。核心 。数据 管理员方面有问题。 我在管理页面尝试LoginFilter。当我运行项目时,页面转发到/ Account / Login页面,但是它给出了这个错误。

错误页面:

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模型

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

2 个答案:

答案 0 :(得分:2)

问题非常简单 - 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.

您正在尝试使用Autofac将IKullaniciRepository服务注入AccountController,但编译器找不到一个,尽管您已在BootStrapper.cs声明了服务注册

因此,BootStrapper.cs的{​​{1}}可能永远不会被调用。只需在RunConfig中拨打电话(例如BootStrapper.RunConfig())到Application_Start()方法,就可以了。

答案 1 :(得分:0)

@Zephyr 谢谢你的帮助。 我添加了新的global.asax文件。 因为我的Application_Start()没有触发。

在global.asax中 旧的:

 public class MvcApplication : System.Web.HttpApplication
新的一个:`

public class Global : System.Web.HttpApplication`