You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Dec 13, 2018. It is now read-only.
While developing several projects for my clients I've found out that injecting logging services into controllers and services seems to be uncomfortable to use, I have to add a logging service into every constructor of each controller and service. Property injecting works slightly better, but the best way I've found is providing static class which serves as a pseudo context, having scope based service resolution under the hood. It goes like this:
publicstaticclassEnvContext{publicstaticIEnvironmentCurrent{get{//get dependency resolver or whatever di frameworkvarresolver=GlobalConfiguration.DependencyResolver// or whateverusing(varscope=resolver.GetRequestLifetimeScope()){// get services needed, instantiate per request scope // (in non http environments that would be a different scope)// use data from those services, cache data per lifetime scopereturnnew CustomEnvironment();}}}}
public interfaceIEnvironment{// Information about Azure environment - node data, etc.AzureEnvironment Azure {get;}// information about Http environment - url, headers, http method, etcHttpEnvironment Http {get;}// custom user informationCustomUser User {get;}// current logger, we could use several approaches to get it while constructing the context
ILogger Logger {get;}// any other useful data}
Then in any controller or service I can use it like this
// for examplevarshippingAddress=EnvContext.Current.User.ShippingAddress;// logs Azure, Http and User info automatically (as configured) and serializes into JSON or whateverEnvContext.Current.Logger.WriteWarning("Something suspicious is going on");// logs a stringEnvContext.Current.Logger.WriteWarningString("No additional info required");
This was a code written in issue editor to illustrate a concept. It is still fully testable, since it used DI under the hood, and it is comfortable to use. I think it makes sense providing a mechanics for a user to configure such a context and then have it out of the box in aspnet vnext