我目前正在使用內置依賴注入 (DI) 的 .NET Core。
我的應用程式正在使用規則引擎設計模式。
我的規則之一,有一個依賴,它有一個依賴。因此,我必須繼續“更新”依賴項的實體。我覺得好像有更好的方法。
這是我的代碼示例。
這行得通,但我不喜歡我必須更新 DataService 和 Repository。
var rules = new List<IRule>
{
new Rule1(),
new Rule2(new DataService(new Repository(CnnStr))) //This is what I don't like
};
s.AddTransient<IRulesEngine>(sp => new RulesEngine(rules));
我開始設定:
s.AddTransient<IRepository>(sp => new Repository(CnnStr));
s.AddTransient<IDataService>(sp => sp.GetRequiredService<DataService>());
這似乎讓我更接近我想要的。但是,我不知道如何用規則實體串列填充規則串列,而不必更新依賴項(DataService 和 Repo)。
像這樣的東西,但我知道這段代碼是不對的。
var rules = new List<IRule>
{
s.AddTransient<IRule>(sp => sp.GetRequiredService<Rule1>())
s.AddTransient<IRule>(sp => sp.GetRequiredService<Rule2>())
};
s.AddTransient<IRulesEngine>(sp => new RulesEngine(rules));
任何幫助,將不勝感激。
謝謝你。
uj5u.com熱心網友回復:
注冊依賴項,規則需要
s.AddTransient<IRepository>(sp => new Repository(CnnStr));
s.AddTransient<IDataService, DataService>(); // you don't need sp here
然后注冊規則。TryAddEnumerable確保不會有相同介面的重復實作
s.TryAddEnumerable(new[] {
ServiceDescriptor.Transient<IRule, Rule1>();
ServiceDescriptor.Transient<IRule, Rule2>();
});
注冊規則引擎
s.AddTransient<IRulesEngine, RulesEngine>();
請注意,規則引擎應該依賴于 IEnumerable<IRule>
uj5u.com熱心網友回復:
我今天早上開始作業了。
我從很多回復中使用了一點。但是,@Daniel A. White 建議的以下鏈接為我整理了所有內容。
.NET Core 依賴注入 -> 獲取介面的所有實作
也許我像@Jeremey Lakeman 建議的那樣過于復雜。
這是我在 Program.cs 檔案中所做的更改:
s.AddTransient<IRepository>(sp => new Repository(CnnStr));
s.AddTransient<IDataService, DataService>();
s.AddTransient<IRule, Rule1>();
s.AddTransient<IRule, Rule2>();
s.AddTransient<IRulesEngine, RulesEngine>();
加上我對規則引擎所做的更改:
private readonly IEnumerable<IRule> _rules;
public RulesEngine(IEnumerable<IRule> rules)
{
_rules = rules;
}
public void RunRules()
{
foreach (var rule in _rules)
{
rule.Execute(canonical);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/392001.html
