代码之家  ›  专栏  ›  技术社区  ›  Leon Radley

ASP.NET MVC、MVCContrib、Structuremap,让它作为controllerfactory工作?

  •  4
  • Leon Radley  · 技术社区  · 16 年前

    我试图让structuremap正确地创建我的控制器,我使用DI将INewsService注入到NewsController中,这是我仅有的构造函数。

    public class NewsController : Controller
    {
        private readonly INewsService newsService;
    
        public NewsController(INewsService newsService)
        {
            this.newsService = newsService;
        }
    
        public ActionResult List()
        {
            var newsArticles = newsService.GetNews();
            return View(newsArticles);
        }
    }
    

    我用这个代码启动这个应用程序

    public class Application : HttpApplication
    {
        protected void Application_Start()
        {
            RegisterIoC();
            RegisterViewEngine(ViewEngines.Engines);
            RegisterRoutes(RouteTable.Routes);
        }
    
        public static void RegisterIoC()
        {
            ObjectFactory.Initialize(config => {
                config.UseDefaultStructureMapConfigFile = false;
                config.AddRegistry<PersistenceRegistry>();
                config.AddRegistry<DomainRegistry>();
                config.AddRegistry<ControllerRegistry>();
            });
            DependencyResolver.InitializeWith(new StructureMapDependencyResolver());
            ControllerBuilder.Current.SetControllerFactory(typeof(IoCControllerFactory));            
        }
    }
    

    但是Structuremap似乎不想注入INewsService,我得到了错误

    我错过了什么?

    3 回复  |  直到 16 年前
        1
  •  6
  •   Erv Walter    16 年前

    我使用StructureMap提供的“默认约定”机制来避免需要单独配置每个接口。下面是我用来实现这一点的代码:

    My Global.asax在Application_Start(使用MvcContrib中的StructureMap工厂)中有这一行:

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
        ObjectFactory.Initialize(x =>
        {
            x.AddRegistry(new RepositoryRegistry());
        });
        ControllerBuilder.Current.SetControllerFactory(typeof(StructureMapControllerFactory));
    }
    

    public class RepositoryRegistry : Registry
    {
    
        public RepositoryRegistry()
        {
            Scan(x =>
            {
                x.Assembly("MyAssemblyName");
                x.With<DefaultConventionScanner>();
            });
    
        }
    
    }
    

    DefaultConventionScanner查找遵循IsomeThingRother和SomeThingRother命名约定的成对接口/类,并自动将后者关联为前一个接口的具体类型。

    ForRequestedType<ISomethingOrOther>().TheDefaultIsConcreteType<SomethingOrOther>();
    
        2
  •  0
  •   Micah    16 年前

    除非我遗漏了什么,否则您不会告诉StructureMap用于INewsService的具体类型。您需要添加以下内容:

    TheConcreteTypeOf<INewsService>.Is<MyConcreteNewsService>();
    

    我不知道确切的语法,但这正是你所缺少的。指定后,它将知道要将哪个INewsService实例注入控制器。

        3
  •  0
  •   David Keaveny    16 年前

    MvcContrib 项目,它内置了对StructureMap(和Castle/Spring.NET/Unity)的支持,尽管当前的文档不存在(从字面上说,您会得到一个存根wiki页面,这不是一个好迹象)。Erv Walter在此线程中的代码示例演示了如何设置StructureMap集成。