[英]What is the recommended pattern for .NET standard libraries using appsettings and IOptions interface?
[英]Populate base class using IOptions pattern
我正在嘗試使用IOptions
模式填充基類。
我的問題 - 當我填充派生對象Child
,是否也可以填充Base
對象而不必在Child
代碼中引用它,並且不必取消注釋下面“啟動”中的注釋行 [1] ?
配置:
<Child>
<Id>1</Id>
<Username>jdoe</username>
</Child>
啟動:
services.Configure<Child>(Configuration.GetSection("Child"));
//will work if this line is uncommented
//services.Configure<Base>(Configuration.GetSection("Child")); //[1]
對象:
public class Base {
public int Id {get;set;}
}
public class Child : Base {
public string Username {get;set;}
}
服務:
public class BaseService {
private readonly Base _cfg;
public BaseService(IOptions<Base> cfg) { _cfg = cfg.Value; }
public void Get() {
//does not work
//returns null
var _id = _cfg.Id;
}
}
我終於通過使用通用約束解決了這個問題
public class BaseService<T> : where T : Base, new() {
private readonly Base _cfg;
public BaseService(IOptions<T> Tcfg) {
_cfg = Tcfg.Value;
}
public void Get() {
//works now
var _id = _cfg.Id;
}
}
啟動服務DI
services.AddScoped<BaseService<Child>>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.