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

Leo*_*ley 4 structuremap asp.net-mvc dependency-injection

我正在尝试使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用此代码启动应用程序

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));            
    }
}
Run Code Online (Sandbox Code Playgroud)

但Structuremap似乎不想注入INewsService,我得到错误没有为此对象定义无参数构造函数.

我错过了什么?

Erv*_*ter 6

我使用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));
}
Run Code Online (Sandbox Code Playgroud)

RepositoryRegistry类看起来像这样:

public class RepositoryRegistry : Registry
{

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

    }

}
Run Code Online (Sandbox Code Playgroud)

DefaultConventionScanner查找遵循ISomethingOrOther和SomethingOrOther的命名约定的接口/类对,并自动将后者作为前一个接口的具体类型.

如果您不想使用该默认约定机制,那么您将在Registry类中添加代码,以使用以下语法将每个接口明确映射到具体类型:

ForRequestedType<ISomethingOrOther>().TheDefaultIsConcreteType<SomethingOrOther>();
Run Code Online (Sandbox Code Playgroud)