【问题标题】:DRYIOC Parameterless controllerDRYIOC 无参数控制器
【发布时间】:2018-04-15 21:39:58
【问题描述】:

我使用 MVC 设置 dryIoc,因为它是一个 mvc 应用程序,但我最近刚刚在项目中添加了一个 API 控制器。调用 API 控制器时出现错误。 MVC 控制器工作正常

尝试创建类型为“xxxController”的控制器时出错。确保控制器有一个无参数的公共构造函数。”

【问题讨论】:

    标签: asp.net-mvc dependency-injection dryioc


    【解决方案1】:

    这个错误不是来自 DryIoc,而是来自 ASP.NET,它会在 DryIoc 失败后尝试实例化控制器。

    要查找 DryIoc 失败的原因,请将可选参数添加到 container.WithMvc() 方法(如果您使用的是 DryIoc.Mvc 扩展):

    var mvcContainer = container.WithMvc(
        throwIfUnresolved: type => true); // throws DryIoc exc. for any unresolved type
    

    希望实际的异常有助于解决问题。

    【讨论】:

    • 我现在收到此错误“无法解析 IControllerFactory,其中在 0 个 Rules.DynamicServiceProviders 中没有找到服务注册,也没有在 0 个 Rules.UnknownServiceResolvers 中找到任何动态注册”
    【解决方案2】:

    这是我发现的。 在我的 StartUp.cs 中,我有以下代码

    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
    
                var config = new HttpConfiguration();
    
                IContainer container = new Container(rules => rules.WithTrackingDisposableTransients());
    
                RegisterServices(container);
    
                container = container.WithMvc();
    
                ConfigureAuth(app);
        }
    
        public static void RegisterServices(IRegistrator registrator)
        {
    
            registrator.Register(typeof(IxxxRepository), typeof(xxxRepository), Reuse.Singleton);
    
        }
    }
    

    在我的 WebApiConfig.cs 中

                var c = new Container()
                .WithWebApi(config, throwIfUnresolved: type => type.IsController());
            c.Register(typeof(IxxxRepository), typeof(xxxRepository), Reuse.Singleton);
    

    两个控制器(MVC 和 API)现在都可以正常工作。但我不确定这是否是正确的方法。因为现在我需要为两个容器的每个实例注册存储库。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多