【问题标题】:No parameterless constructor defined for this object. MVC 5没有为此对象定义无参数构造函数。 MVC 5
【发布时间】:2021-12-21 01:24:23
【问题描述】:

当我尝试使用 .NET Framework(4.7.2) 和 EF Core(3.0) 进行编码时遇到问题,因为我通常使用 .NET Core。 当我尝试注入存储库时(通过它的接口)。

这是我的代码

SenderController.cs

public class SenderController : Controller
{
    private readonly ISenderRepository _sRepo;
    public SenderController(ISenderRepository sRepo)
    {
        _sRepo = sRepo;
    }

    public ActionResult Index()
    {
        return View();
    }

ISenderRepository.cs

 public interface ISenderRepository
{
    ICollection<Sender> GetSenders();
    Sender GetSender(int senderId);
    bool SenderExists(string name);
    bool SenderExists(int id);
    bool CreateSender(Sender sender);
    bool UpdateSender(Sender sender);
    bool DeleteSender(Sender sender);
    bool Save();
}

这就是我得到的

我认为我在 MVC 5 中为依赖注入做错了。你能帮我做吗? 谢谢你:)

【问题讨论】:

  • “我在尝试使用 .NET Framework(4.7.2) 和 EF Core(3.0) 进行编码时遇到问题” - 选择一个。
  • 你能发布 SenderRepository 类吗?问题很可能在实施中。不在界面中。
  • 对不起,我只是通过在构造函数中使用它来找到答案:private ISenderRepository _sRepo; public SenderController() { this._sRepo = new SenderRepository(new Data.ApplicationDbContext()); }
  • 你能展示你的依赖注入配置吗?

标签: c# .net asp.net-mvc dependency-injection


【解决方案1】:

确保你必须注入你的控制器,你可以使用 Autofac 来帮助你

【讨论】:

    【解决方案2】:

    我只是通过在构造函数中使用这个语句来修复它:

    private ISenderRepository _sRepo;
        public SenderController()
        {
            this._sRepo = new SenderRepository(new Data.ApplicationDbContext());
        }
    

    谢谢

    【讨论】:

    • 这不是修复,只是没有使用依赖注入。太糟糕了。
    • 那么如何真正解决它?
    • 正如您所写,您的 DI 配置不正确。请将其添加到您的问题中。
    • 当我在 Core 中使用 DI 时我仍然感到困惑,只需添加 AddScoped 。我可以在 .net Framework 的什么地方使用它?
    • 在 .NET Framework 中,您必须使用第三方 DI 库(Simple Injector 是我最喜欢的,但 YMMV),并使用 DependencyResolver.SetResolver() API 将其拼接到 MVC。以下是 Simple Injector 的工作方式:docs.simpleinjector.org/en/latest/mvcintegration.html
    猜你喜欢
    • 2018-02-11
    • 1970-01-01
    • 2010-11-24
    • 2013-04-25
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多