Skip to content
This repository was archived by the owner on Dec 13, 2018. It is now read-only.
This repository was archived by the owner on Dec 13, 2018. It is now read-only.

Consider having easy way to access and log custom data as a sort of pseudo context #57

@eugeneagafonov

Description

@eugeneagafonov

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:

public static class EnvContext 
{
  public static IEnvironment Current 
  {
     get 
     {
         //get dependency resolver or whatever di framework
         var resolver = GlobalConfiguration.DependencyResolver // or whatever
         using (var scope = 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 scope
             return new CustomEnvironment();
         }
     }
  }  
}

public interface IEnvironment
{
  // Information about Azure environment - node data, etc.
  AzureEnvironment Azure { get; }

  // information about Http environment - url, headers, http method, etc
  HttpEnvironment Http { get; }

  // custom user information
  CustomUser 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 example
var shippingAddress = EnvContext.Current.User.ShippingAddress;

// logs Azure, Http and User info automatically (as configured) and serializes into JSON or whatever
EnvContext.Current.Logger.WriteWarning("Something suspicious is going on");

// logs a string
EnvContext.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

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions