如果我們將委託註冊爲組件,則AutowiringParam在解析時將採用與NamedParameter相同的優先級!Autofac無法在兩個構造函數之間進行解析(如果明確更具體)
這裏有一個歸結例如:
public class AParam { }
public class BParam : IParam { }
public interface IParam { }
public interface IAThing { }
public class AThing : IAThing
{
public AThing(AParam aParam) { }
public AThing(BParam anotherParam) { }
}
static void Main(string[] args)
{
IContainer c = (new ContainerBuilder()).Build();
var anotherBuilder = new ContainerBuilder();
anotherBuilder.RegisterType<AThing>().As<IAThing>().InstancePerDependency();
anotherBuilder.Register((context, parm) => new BParam()).As<BParam>().InstancePerDependency();
anotherBuilder.Update(c);
object aParam = new AParam();
//Throws exception, it's unable to decide which constructor to use....
var instance = c.Resolve(typeof(IAThing), new[] {new NamedParameter("aParam", aParam) });
}
在這種情況下,我指定正是我想要的NamedParameter「aParam」,但AutowiritingParameter可以填寫在BParam,所以它不知道哪個構造函數可以選擇(因爲它們的參數長度都相等)。
我該怎麼做才能讓Autofac優先使用我提到的指定參數的特定構造函數?沒有理由爲什麼我想讓我的參數被忽略,如果它使用AutowiringParameter就會是這種情況。
我可以使用「UsingConstructor」,但只要BParam派生自AParam,我們就會回到相同的含糊之處。 在這裏,我明確要求具有命名參數的構造函數。 任何想法?
編輯:
使用在構造函數默認參數可以使Autofac忽略用戶指定的命名參數完全,沒有錯誤,你不會發現!
public class AThing : IAThing
{
public AThing(AParam aParam) { }
public AThing(BParam anotherParam, bool def = true) { }
}
我注意到你的'Resolve'使用'typeof(IAThing)'但不是具體類'AThing'你試圖指定構造函數嗎?另外,[this](http://docs.autofac.org/en/latest/register/registration.html#selection-of-an-implementation-by-parameter-value)能爲您提供任何幫助嗎?它還說「如果創建實例的委託被聲明並且使用委託工廠,則可以實現清潔,類型安全的語法。」您可能可以通過代理和委託工廠解決此問題。 – ErikE
嗨,Erik, 一般來說,我們使用Autofac進行依賴注入,所以它可能不是我們正在試圖解決的AThing(可能是測試模型),但絕對是帶有命名參數「aParam」的構造函數。 我不明白爲什麼Autofac使用「AutowiringParameter」作爲構造函數向「aParam」構造函數賦值相同的「特異性」(以下將其用於使用舊版本的Autofac):/它的某種忽略我想要一個特定的參數名稱(鍵入的參數結果相同的問題btw) 感謝您的回覆 – GettnDer
這是您的應用程序組件具有多個構造函數的反模式,詳細解釋[這裏](https:// www。 cuttingedge.it/blogs/steven/pivot/entry.php?id=97)。 – Steven