ipjohnson / Grace

Grace is a feature rich dependency injection container library
MIT License
336 stars 33 forks source link

Logging using DI #141

Closed xp-development closed 6 years ago

xp-development commented 6 years ago

Hi. Because of the great performance, we try to migrate our project from Ninject to Grace. Now I try to configure our own ILog interface by using DI.

Ninject configuration: container.Bind<ILog>().ToMethod(context => logProvider.GetLogger(context?.Request.Target?.Member.DeclaringType)).InTransientScope();

Is it possible to get the type of the object that request ILog?

Sample:

DependencyInjectionContainer container = new DependencyInjectionContainer();
//????? container.Configure(c => c.ExportFunc(logProvider.GetLogger));
container.Configure(c => c.Export<BasicService>().As<IBasicService>());

public class BasicService : IBasicService
{
  private readonly ILog _log;

  public BasicService(ILog log)
  {
    _log = log;
  }

  public void Print()
  {
    _log.Debug("Basic");
  }
}

public class Log : ILog
{
  private readonly Type _requestedType;

  public Log(Type requestedType)    // <----------- should be typeof(BasicService)
  {
    _requestedType = requestedType;
  }
}
ipjohnson commented 6 years ago

Hi @jan-schubert

You want to do something like this

container.Configure(c => c.ExportFactory<StaticInjectionContext, ILog>(
         context => logProvider.GetLogger(context?.TargetInfo.InjectionType)));
xp-development commented 6 years ago

Thank you. Now I found a unit test for my case (FactorySpecialTypeTests.Factory_Depend_On_IExportLocatorScope_StaticContext).