2014-09-30 89 views
0

我想在Autofac中註冊/解析泛型類型,它接收一個類型參數,它是一個接口並且已經被註冊了。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>()

有什麼想法?

回答

0

我有類似的問題,最有可能出於同樣的原因,即因爲實體框架無法使用接口。我通過使用Autofac的OnActivating方法see documentation here找到該類型,然後調用新實例內的方法來設置類型來解決此問題。

看着OnActivating文檔,他們展示了一個你用新的替換實例的情況,這就是你想要的。要創建新實例做到這一點,你需要做兩件事情:

  1. 解決的IEntity到實體類
  2. 創建自己的泛型類。

第一個問題的答案在我的stackoverflow post中,所以我在這裏不再重複。

第二個很簡單。你需要使用.NET MakeGenericType方法來創建類,在你的情況下代碼會是這樣的。

e.ReplaceInstance(typeof(NhRepository<>).MakeGenericType(new []{resolvedType})); 

其中resolvedType通過從我的溶液中的命令foundEntry.Activator.LimitType取代。希望這是有道理的。

+0

它不起作用,因爲您無法將NhRepository 轉換爲IRepository ,無論實現各個接口的類如何。 – 2017-04-27 02:17:24