![](/img/trans.png)
[英]Trying to resolve an interface implementation based on generic type passed at runtime in autofac
[英]Autofac resolve generic type with interface as a param
我試圖在Autofac中注冊/解析泛型,該泛型接受類型參數,這是一個接口,也已經注冊過。
我有以下幾點:
public interface IBaseEntity
{
}
public partial interface IRepository<T>
where T : IBaseEntity
{
}
public class NhRepository<T> : IRepository<T>
where T : IBaseEntity
{
}
public interface IEntity : IBaseEntity
{
}
public class Entity : IEntity
{
}
注冊:
//registering type
builder.RegisterType<Entity>().As<IEntity>();
//registering generic type in Autofac
builder.RegisterGeneric(typeof(NhRepository<>))
.As(typeof(IRepository<>)).InstancePerRequest();
嘗試解決:
//the code below returns NhRepository<IEntity>().
_containerManager.Resolve<IRepository<IEntity>>();
我想要一個方法來獲取NhRepositoy<Entity>
而不是NhRepository<IEntity>()
任何想法?
我有一個類似的問題,很可能是出於與您相同的原因,即因為Entity Framework無法使用接口。 我通過使用Autofac的OnActivating
方法解決了該問題, 請參見此處的文檔以查找類型,然后在新實例內部調用一個方法來設置類型。
查看OnActivating
文檔,他們顯示了用新實例替換實例的情況。 要創建新實例,您需要做兩件事:
第一個答案是在我的stackoverflow帖子中 ,所以我在這里不再重復。
第二個很簡單。 您需要使用.NET MakeGenericType
方法來創建類,在這種情況下,代碼將是類似的。
e.ReplaceInstance(typeof(NhRepository<>).MakeGenericType( new []{resolvedType}));
在我的解決方案中, resolvedType
替換為foundEntry.Activator.LimitType
命令。 希望有道理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.