首页 > 解决方案 > 为什么 Unity 在解析类时无法选择 String 构造函数?

问题描述

我已经在(.NET 4.5.2)项目中将 Unity 从 v4.0.1 升级到 v5.11.3,该项目之前运行良好,但自从我升级后,我得到以下异常: Resolution failed with error: Failed to select a constructor for System.String

我要解析的类有一个 String 构造函数,我已经用InjectionConstructor. 请参见下面的代码:

// Multiple IDbContext registrations happen when the application is initialized
container.RegisterType<IDbContext, AuthenticationContext>(typeof(AuthenticationContext).ToString(), new InjectionConstructor(AppConstants.DatabaseKey));
container.RegisterType<IDbContext, ApplicationContext>(typeof(ApplicationContext).ToString(), new InjectionConstructor(AppConstants.DatabaseKey));

public class DbContextFactory : IDbContextFactory
{
   private readonly IUnityContainer _container;

   public DbContextFactory(IUnityContainer container)
   {
      _container = container;
   }

   public IDbContext CreateDbContext<TDbContext>() where TDbContext : IDbContext
   {
      var key = typeof(TDbContext).ToString();
      return container.Resolve<TDbContext>(key);
   }
}

public class AuthenticationContext : DbContextWrapper
{
   public AuthenticationContext(string connectionString) : base(connectionString)
   {
   }
}

public class DbContextWrapper : IDbContext
{
   public DbContextWrapper(string connectionString)
   {
   }
}

我应该如何解释异常?无法为 String 选择构造函数,让我认为注册成功并且它正在寻找一个接受 String 但找不到它的构造函数?这很奇怪,因为我的 AuthenticationContext 只有一个接受...字符串的构造函数!

我尝试在 dotnetfiddle 上澄清一个完整的代码示例,但是在初始化 UnityContainer 时出现“操作可能破坏运行时的稳定性”异常。见https://dotnetfiddle.net/xuX57K

标签: c#dependency-injectionunity-containerconstructor-injection

解决方案


所以我在启用调试模式后得到的新异常消息container.EnableDebugDiagnostic();让我思考......这就是说我必须配置容器为构造函数提供字符串值,我确信我做到了。所以这意味着它实际上甚至没有考虑使用我的注册。在调试容器注册时,我看到我的注册在那里,所以这也不是问题。

然后我意识到Unity默认注册所有类型,所以它试图创建一个实例,AuthenticationContext因此失败了,因为当它使用隐式注册时,它不知道如何处理所需的字符串参数。

错误在DbContextFactory,这修复了它:

public IDbContext CreateDbContext<TDbContext>() where TDbContext : IDbContext
{
   var key = typeof(TDbContext).ToString();

   // This is wrong because it is trying to resolve AuthenticationContext for a given name.
   // But it should resolve a registration for IDbContext for that name since that is
   // how it was registered!
   // return container.Resolve<TDbContext>(key);

   return container.Resolve<IDbContext>(key);
}

推荐阅读