How to configure StructureMap for asp.net MVC 5

前端 未结 4 2201
Happy的楠姐
Happy的楠姐 2021-02-02 14:29

I\'m getting below error. I setup it similar to asp.net mvc 4.

No parameterless constructor defined for this object. Description: An unhandled exception

4条回答
  •  眼角桃花
    2021-02-02 14:42

    The following steps worked for me:

    1. Create a new ASP.NET MVC 5 application in Visual Studio 2013 RTM
    2. Install the StructureMap.MVC4 NuGet:

      Install-Package StructureMap.MVC4
      
    3. Create a new interface:

      public interface IDependency
      {
          string SayHello();
      }
      
    4. Implement this interface:

      public class ConcreteDepenedency: IDependency
      {
          public string SayHello()
          {
              return "Hello World";
          }
      }
      
    5. Have the HomeController work with this interface:

      public class HomeController : Controller
      {
          private readonly IDependency dependency;
          public HomeController(IDependency dependency)
          {
              this.dependency = dependency;
          }
      
          public ActionResult Index()
          {
              return Content(this.dependency.SayHello());
          }
      }
      
    6. Configure your container in ~/DependencyResolution/Ioc.cs:

      using StructureMap;
      using WebApplication1.Controllers;
      
      namespace WebApplication1.DependencyResolution {
      
          public static class IoC {
      
              public static IContainer Initialize() {
      
                  ObjectFactory.Initialize(x =>
                  {
                      x.For().Use();
                  });
      
                  return ObjectFactory.Container;
              }
          }
      }
      
    7. Run your application with Ctrl+F5

    8. The ConcreteDependency is successfully injected in HomeController.

提交回复
热议问题