如何解决在Mvc中没有为此对象错误定义无参数构造函数的问题? [英] How to solve No parameterless constructor defined for this object error in Mvc?

查看:287
本文介绍了如何解决在Mvc中没有为此对象错误定义无参数构造函数的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个演示应用程序,以学习如何使用存储库模式执行插入操作.我正在使用Nop Commerce **( http://www.nopcommerce.com )**存储库模式的代码

错误:未为此对象定义无参数构造函数

我看过以下链接: MVC:未定义无参数构造函数为此对象

这是我的结构:

我的存储库界面:

public partial interface IRepository<T>
    {
        void Insert(T entity);
     }

我的服务层:

 public partial interface IEmployeeService
    {
        void InsertCategory(EmployeeMaster employeeMaster);
    }

将实现该接口(服务)的我的班:

public partial class EmployeeService : IEmployeeService
    {
        #region Fields
        private readonly IRepository<EmployeeMaster> _employeeMasterRepository;
        #endregion

        #region Ctor
        public EmployeeService
            (
            IRepository<EmployeeMaster> employeeMasterRepository
            )
         {
             this._employeeMasterRepository = employeeMasterRepository;
         }

        #endregion



public virtual void InsertCategory(EmployeeMaster employeeMaster)
        {
            if (employeeMaster == null)
                throw new ArgumentNullException("employeeMaster");

            _employeeMasterRepository.Insert(employeeMaster);
}

这是我的控制者:

public class HomeController : Controller
    {
        #region Fields
        private readonly IEmployeeService  _employeeService;
        #endregion

 #region Constructors
        public HomeController
        (
            IEmployeeService employeeService
        )
        {
            this._employeeService = employeeService;
        }
        #endregion

获取错误:没有为此对象定义无参数构造函数

我对此错误进行了研究,所有消息人士都说使用依赖注入来解决此错误.

有人可以指导我如何使用依赖注入来解决此错误吗?

解决方案

您是正确的-您需要使用Unity,Ninject或Autofac之类的东西才能使它运行.

基本上-无论使用哪种技术,步骤都大致相同.

以团结为例:

1)在您的MVC项目中,使用NuGet添加用于MVC的Unity Bootstrapper". (右键单击引用,管理nuget程序包,在线搜索 unity ,选择用于MVC的Unity Bootstrapper"

这将为您的项目添加一些内容-最有趣的是App_start中的unityConfig.cs.

2)在unityConfig.cs中-找到 RegisterTypes 方法

RegisterTypes 是您告诉统一容器当您需要X之一时,使用实现Y" –在您的情况下,当您需要IEmployeeService时,使用EmployeeService"

3)在寄存器类型中-添加类型映射-例如,在您的情况下:

container.RegisterType<IEmployeeService, EmployeeService>();

AND

4)稍微复杂一点:因为您拥有IRepository ,并且需要使用它来正确解析employeeService ,所以您还必须针对通用实现注册通用类型(有点奇怪).查看您的类型,将会是这样:

container.RegisterType(typeof(IRepository<>),typeof(Repository<>));

(您需要根据您的项目解析名称空间).

所以-这是在说什么...

正确的MVC-当您需要IEmployeeService时,请使用employeeService,并且 当您需要一个IRepository<>时,请使用Repository<>

现在-由于在NuGet安装过程中添加了webActivator(在UnityConfig.cs的隔壁),应该是它-webActivator将DependencyResolver.Current设置为使用此unityContainer的对象.

因此,MVC现在在尝试实例化控制器时会使用此新的unityContainer,从而解决了类型映射.

webActivator和unityConfig类为您做了很多繁重的工作,只是精心设计的registerTypes,并且您至少应该在解决方案中立足.

HTH-祝你好运.

PS-DI本身是一个巨大的主题-在这里太多了,您会碰到各种各样的奇怪和奇妙的事情(为解决方案提供Ctor args,只是一开始就进行生命周期管理!)-这很有趣,但是并非微不足道,所以如果这不能开箱即用",您必须原谅我(认为这样做几乎是不切实际的)-这只是模糊的尝试,使您在该主题上立足!/p>

有关统一的更多信息-建议您阅读http://www.nopcommerce.com) **code for repository pattern

Error:No parameterless constructor defined for this object

I have seen this link:MVC: No parameterless constructor defined for this object

This is my Structure:

My Repository interface:

public partial interface IRepository<T>
    {
        void Insert(T entity);
     }

My Service Layer:

 public partial interface IEmployeeService
    {
        void InsertCategory(EmployeeMaster employeeMaster);
    }

My Class which will implement that interface(service):

public partial class EmployeeService : IEmployeeService
    {
        #region Fields
        private readonly IRepository<EmployeeMaster> _employeeMasterRepository;
        #endregion

        #region Ctor
        public EmployeeService
            (
            IRepository<EmployeeMaster> employeeMasterRepository
            )
         {
             this._employeeMasterRepository = employeeMasterRepository;
         }

        #endregion



public virtual void InsertCategory(EmployeeMaster employeeMaster)
        {
            if (employeeMaster == null)
                throw new ArgumentNullException("employeeMaster");

            _employeeMasterRepository.Insert(employeeMaster);
}

This is my controller:

public class HomeController : Controller
    {
        #region Fields
        private readonly IEmployeeService  _employeeService;
        #endregion

 #region Constructors
        public HomeController
        (
            IEmployeeService employeeService
        )
        {
            this._employeeService = employeeService;
        }
        #endregion

Getting Error:No parameterless constructor defined for this object

I have studied regarding this error and all the sources are saying that use Dependency injection to solve this error.

Can anybody guide me how to use dependency injection to solve this error??

解决方案

You're correct - you'll need to use something like Unity, Ninject or Autofac to get this running.

Essentially - the steps are roughly the same regardless of the tech used.

Using unity as an example:

1) In your MVC project, use NuGet to add "Unity Bootstrapper for MVC". (right click references, manage nuget packages, search for unity online, select "Unity Bootstrapper for MVC"

This will add a few things to your project - the most interesting is the unityConfig.cs in App_start.

2) In unityConfig.cs - find RegisterTypes method

RegisterTypes is where you tell the unity container "when you need one of X, use implementation Y" - in your case "when you need an IEmployeeService, use EmployeeService"

3) In register types - add your type mappings - for example, in your case:

container.RegisterType<IEmployeeService, EmployeeService>();

AND

4) Bit more complicated: as you have IRepository and you need this to resolve your employeeService correctly you'll also have to register a generic type against a generic implementation (it's a little odd). Looking at your types, it's going to be something like:

container.RegisterType(typeof(IRepository<>), typeof(Repository<>));

(You'll need to resolve the namespaces according to your projects).

So - what this is saying is...

Right MVC - when you need an IEmployeeService use employeeService, and when you need an IRepository<>, use Repository<>

Now - because of the webActivator that was added during the NuGet installation (right next door to UnityConfig.cs), that should be it - the webActivator sets the DependencyResolver.Current to something that uses this unityContainer.

Beacause of this, MVC will now use this new unityContainer whenever it tries to instantiate your controllers, resolving the type mappings on the way.

The webActivator and unityConfig classes do alot of the heavy-lifting for you, just elaborate registerTypes and you should at least have a foot-hold in the solution.

HTH - good luck.

PS - DI itself is a massive subject - far too much for here, you'll bump into all sort of weird and wonderful things (supplying Ctor args for resolutions, lifetime management just for a start!) - it's fun, but not trivial, so you'll have to excuse me if this doesn't work "out of the box" (it's almost impractical to think it would) - this is merely just a vague attempt to give you a foothold in the subject!

For more info on unity - I suggest you read up here (Dev guide to using Unity on MSDN)

这篇关于如何解决在Mvc中没有为此对象错误定义无参数构造函数的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆