gpt4 book ai didi

c#-4.0 - 如何为 asp.net MVC 5 配置 StructureMap

转载 作者:行者123 更新时间:2023-12-03 13:42:02 25 4
gpt4 key购买 nike

我正在低于错误。我设置它类似于 asp.net mvc 4。

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.



异常详细信息:System.MissingMethodException:没有为此对象定义无参数构造函数。

终于发现实际异常“尝试获取HomeController类型的实例时发生激活错误,键“””

当我要将服务类注入(inject)家庭 Controller 时发生错误

最佳答案

以下步骤对我有用:

  • 在 Visual Studio 2013 RTM
  • 中创建一个新的 ASP.NET MVC 5 应用程序
  • 安装 StructureMap.MVC4 NuGet:
    Install-Package StructureMap.MVC4
  • 创建一个新界面:
    public interface IDependency
    {
    string SayHello();
    }
  • 实现这个接口(interface):
    public class ConcreteDepenedency: IDependency
    {
    public string SayHello()
    {
    return "Hello World";
    }
    }
  • 让 HomeController 使用这个接口(interface):
    public class HomeController : Controller
    {
    private readonly IDependency dependency;
    public HomeController(IDependency dependency)
    {
    this.dependency = dependency;
    }

    public ActionResult Index()
    {
    return Content(this.dependency.SayHello());
    }
    }
  • ~/DependencyResolution/Ioc.cs 中配置您的容器:
    using StructureMap;
    using WebApplication1.Controllers;

    namespace WebApplication1.DependencyResolution {

    public static class IoC {

    public static IContainer Initialize() {

    ObjectFactory.Initialize(x =>
    {
    x.For<IDependency>().Use<ConcreteDepenedency>();
    });

    return ObjectFactory.Container;
    }
    }
    }
  • 使用 Ctrl+F5
  • 运行您的应用程序
  • ConcreteDependency成功注入(inject)HomeController .
  • 关于c#-4.0 - 如何为 asp.net MVC 5 配置 StructureMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19476856/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com