[英]Why does Unity fail to select a String constructor when resolving class?
我已經在之前運行良好的 (.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();
啟用調試模式后得到的新異常消息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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.