简体   繁体   中英

Populate base class using IOptions pattern

I am trying to populate a base class using the IOptions pattern.

My question -- When I populate the derived object Child , is it possible to populate the Base object as well without having to reference it within the Child code AND without having to uncomment the commented line[1] in "Startup" below?

Config:

<Child>
    <Id>1</Id>
    <Username>jdoe</username>
</Child>

Startup:

services.Configure<Child>(Configuration.GetSection("Child"));

//will work if this line is uncommented
//services.Configure<Base>(Configuration.GetSection("Child")); //[1]

Objects:

public class Base {    
    public int Id {get;set;}    
}

public class Child : Base {    
    public string Username {get;set;}    
}

Service:

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;
    }
}

I finally resolved this by using generic constraints

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;
    }
}

Startup Service DI

services.AddScoped<BaseService<Child>>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM