![](/img/trans.png)
[英]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.