dependency injection - Getting the host name from a scoped service factory -


one of services i'm creating needs current host name parameter (different requests use different host names, affects external resources used service):

public class foo {     public foo(string host) {...} } 

i'm registering scoped:

public void configureservices(iservicecollection services) {     services.addscoped(s => new foo(/* host name current request */)); } 

what cleanest way host name @ point?


update: came this:

private static foo getfoo(iserviceprovider services) {     var contextaccessor = services.getrequiredservice<ihttpcontextaccessor>();     var host = contextaccessor.httpcontext.request.host.value;     return new foo(host); } 

is good/supported solution, or hack?

since you're correctly defining scoped already, can use ihttpcontextaccessor directly in constructor of foo:

public class foo {     public foo(ihttpcontextaccessor contextaccessor)      {         var host = contextaccessor.httpcontext.request.host.value;         // remainder of constructor logic here     } } 

something similar done many places in github repositories; looks perfect pattern follow.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -