OptionsModel dependency injection in vNext console application -
i have vnext console application 1 of classes takes optionsmodel<t>
poco configuration settings class.
i unable poco settings class resolved , injected rabbitmqconnection
class below.
setting serviceprovider
not issue, it's resolution of settings class.
note, vnext console application (not mvc6 app).
my second question is, , understand constructor arguments should kept minimal, not best pass 2 strings constructor arguments rather ioptions
class former method more descriptive of rabbitmqconnection
class requires? if so, how best injected class defined mappings (program.cs
file in example below)
public class rabbitmqconnection { public string hostname { get; set; } public string username { get; set; } public rabbitmqconnection(ioptions<messagingsettings> settings) { hostname = settings.value.hostname; username = settings.value.username; } } public class messagingsettings { public string hostname { get; set; } public string username { get; set; } } appsettings.json { "messagingsettings":{ "hostname":"localhost", "username":"guest" } } public void configureservices(iservicecollection services) { // tried registration number of ways below services.configure<messagingsettings>(configuration.getsection("messagingsettings")); services.configure<messagingsettings>(configuration); // attempt 1 - runtime error saying cant resolve ioptions<messagesettings> services.tryadd(servicedescriptor.singleton<rabbitmqconnection, rabbitmqconnection>()); // attempt 2 - same above, when breakpoint on messagingsettings, values in object null services.tryadd(servicedescriptor.singleton<rabbitmqconnection>(factory => { // instead of injecting messagesettings, pass through string values (constructor omitted clarity) var messagingsettings = configuration.get<messagingsettings>(); return new rabbitmqconnection(messagingsettings.hostname, messagingsettings.username); })); } var conn = serviceprovider.getrequiredservice<rabbitmqconnection>();
you need call services.addoptions()
Comments
Post a Comment