我正在尝试使用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(); config.AddRegistry (); config.AddRegistry (); }); DependencyResolver.InitializeWith(new StructureMapDependencyResolver()); ControllerBuilder.Current.SetControllerFactory(typeof(IoCControllerFactory)); } }
但Structuremap似乎不想注入INewsService,我得到错误没有为此对象定义无参数构造函数.
我错过了什么?
我使用StructureMap提供的"默认约定"机制来避免需要单独配置每个接口.下面是我用来完成这项工作的代码:
我的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)); }
RepositoryRegistry类看起来像这样:
public class RepositoryRegistry : Registry { public RepositoryRegistry() { Scan(x => { x.Assembly("MyAssemblyName"); x.With(); }); } }
DefaultConventionScanner查找遵循ISomethingOrOther和SomethingOrOther的命名约定的接口/类对,并自动将后者作为前一个接口的具体类型.
如果您不想使用该默认约定机制,那么您将在Registry类中添加代码,以使用以下语法将每个接口明确映射到具体类型:
ForRequestedType().TheDefaultIsConcreteType ();