【问题标题】:Dependency Injection Issue of Two MVC Projects in the Same solution同一解决方案中两个 MVC 项目的依赖注入问题
【发布时间】:2018-04-26 09:44:39
【问题描述】:

我有一个包含单个 MVC 项目的 Web 解决方案。我在这个项目中使用了 Ninject 绑定来进行构造函数注入,并且效果很好。现在我在同一个解决方案中添加了另一个 MVC 项目,并在这个新项目中也使用了构造注入。新项目成为启动项目。但是在项目运行的时候,会报错,叫做“No parameterless constructor defined for this object”。如果我在相应的控制器中添加一个无参数的构造函数,这个错误就会消失。但构造函数绑定不会发生,因为此时调用了无参构造函数。我什至尝试创建一个单独的库来解决依赖关系并在 MVC 项目中使用该 DLL。但这会产生循环依赖,因此没有成功。 这种情况应该怎么解决?

【问题讨论】:

    标签: asp.net asp.net-mvc web dependency-injection ninject


    【解决方案1】:

    我过去通过在Global.asax.cs 中调用MapperConfig.RegisterMaps(); 并定义RegisterMaps() 方法如下解决了这个问题:

    public class MapperConfig
      {
        public static void RegisterMaps()
        {
          //get all projects' AutoMapper profiles using reflection
          var assembliesToScan = System.AppDomain.CurrentDomain.GetAssemblies();
          var allTypes = assembliesToScan.SelectMany(a => a.ExportedTypes).ToArray();
    
          //depending on your solution, you may need allTypes to be defined as:
          //var allTypes = assembliesToScan.Where(x => !x.IsDynamic).SelectMany(a => a.ExportedTypes).ToArray();
    
          var profiles =
              allTypes
                  .Where(t => typeof(Profile).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo()))
                  .Where(t => !t.GetTypeInfo().IsAbstract);
    
          //add each profile to our static AutoMapper
          Mapper.Initialize(cfg =>
          {
            foreach (var profile in profiles)
            {
              cfg.AddProfile(profile);
            }
          });
        }
      }
    

    然后在解决方案的每个项目中,您可以拥有单独的自动映射器配置文件(我喜欢这样,以便您的自动映射器绑定在使用它们的层中定义,而不是将所有映射放入 1 个巨大的文件中),如下所示:

      public class AutoMapperServicesConfig : Profile
      {
        public AutoMapperServicesConfig()
        {
          CreateMap<Entity, EntityViewModel>();
        }
    
        public override string ProfileName
        {
          get { return this.GetType().ToString(); }
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 2020-01-02
      • 1970-01-01
      相关资源
      最近更新 更多