c# - 为什么 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
解决方案
所以我在启用调试模式后得到的新异常消息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);
}
推荐阅读
- c# - 在控制器 Web API 中创建自定义错误 401 响应
- python - 使用 SWIG 围绕 C++ 的 Python 包装器。参数类型无法识别
- react-native - React Native SearchBar Invariant Violation 错误'预期的功能,而不是对象的值'
- c# - 从 API 获取 json 对象,使用 C# 修改并发布它
- firebase - 如何解决〜在 null 上调用了 getter 'documentID'。〜?
- angular - Angular 6 与 Angular Material、sweetalert 和 webpack
- android - Firebase 之外的推送通知和电话身份验证服务
- amazon-web-services - Terraform for_each 变量以创建多个 AWS 侦听器规则并设置唯一的 target_group_arn
- python - 如何在python的循环中定义缩进
- powershell - 如何在 powershell 命令行中使用 FTP 将文件上传到 OneDrive