2016-03-18 80 views
0
public class Sub1 : Base<SomeClass> 
{ 
    // for sake of getting injection to work, not injecting anything in ctor 
    public Sub1() {} 
    .... 
} 

public class Sub2 : Base<SomeOtherClass> 
{ 
    // for sake of getting injection to work, not injecting anything in ctor 
    public Sub2() {} 
    .... 
} 

public abstract class Base<T> 
{ 
    // abstract, so no ctor 
    .... 
} 

我試過以下,但我得到下面列出的例外。注意它的異常引用了Base抽象類。我錯過了什麼?autofac註冊關閉抽象的子類的開放式通用

builder.RegisterAssemblyTypes(typeof(Base<>).Assembly) 
       .Where(t => t.IsSubclassOf(typeof(Base<>))).AsClosedTypesOf(typeof(Base<>)).InstancePerDependency(); 

上類型沒有構造 'Base`1 [SomeClass的]' 可以與構造取景 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' 找到。

+0

你可以顯示你的構造函數的實現。 –

+0

編輯顯示簡單的構造函數。我假設我在註冊中丟失了一些東西,但我不知道是什麼。 – Suedeuno

回答

2

我認爲你混合了泛型和非泛型抽象類註冊。

您有通用的抽象類。因此你的註冊應該是這樣的:

builder.RegisterAssemblyTypes(typeof(Base<>).Assembly).AsClosedTypesOf(typeof(Base<>)).InstancePerDependency(); 
+0

仍然得到例外。嘗試添加一個IRepository <>接口到抽象和做builder.RegisterAssemblyTypes(typeof(IBase <>)。Assembly).AsClosedTypesOf(typeof(IBase <>));但即使我已經看到說明它的博客,這也不起作用。 – Suedeuno

+0

你能分享你的解決方式嗎?我沒有得到錯誤。 –

+1

我看到問題,我嘗試解決的特定泛型類型的封閉類型位於未註冊的另一個程序集中。這意味着我在IBase的程序集中註冊了類型,但<>中的類型在另一個程序集中,我沒有註冊。謝謝你的幫助。 – Suedeuno