加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.NET MVC,MVCContrib,Structuremap,让它作为c

发布时间:2020-12-16 06:41:27 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试使用structuremap来正确创建我的控制器,我正在使用DI将一个INewsService注入一个NewsController,这是我唯一的构造函数. public class NewsController : Controller{ private readonly INewsService newsService; public NewsController(INewsServi
我正在尝试使用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,我得到了错误
没有为此对象定义的无参数构造函数.

我错过了什么?

解决方法

我使用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>();
        });

    }

}

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

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

ForRequestedType<ISomethingOrOther>().TheDefaultIsConcreteType<SomethingOrOther>();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读