[英]How to resolve dependency based on type as string using Autofac
我有一個通用接口,例如IGeneric
,我想根據我作為string
的類型動態解析。 為了更加清楚,我可以像這樣解決依賴關系:
container.Resolve<IGeneric<AType>>();
但是我的問題是當我遇到這個問題時該如何解決:
var type = "AType";
除了(優於)將可以代替AType
使用的每個可能的類注冊為命名實例之外,還有其他方法嗎?
使用接受Type
的Resolve原型。
Type type = System.Type.GetType("AType");
var instance = container.Resolve(type);
或者(不確定要使用哪一個)來解決IGeneric<Atype>
使用:
Type genericType = typeof(IGeneric<>);
Type specificType = genericType.MakeGenericType(new [] {Type.GetType("AType")});
var instance = container.Resolve(specificType );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.