Grace icon indicating copy to clipboard operation
Grace copied to clipboard

Incorrect behavior when call Inject from a child container

Open mcdis opened this issue 2 years ago • 1 comments

public class Log : ILog
{
  public Log(string _scope)
  {
    Scope = _scope;
  }
  public string Scope { get; }
  public ILog this[string _subScope] => new Log($"{Scope}/{_subScope}");
  public string? Trace(string? _message)
  {
    if (_message is not null)
      Android.Util.Log.Error(Scope, _message);
    return _message;
  }
}

Main app:

  Scope = new DependencyInjectionContainer(_ =>
    {
      _.Behaviors.ConstructorSelection = ConstructorSelectionMethod.Dynamic;
      _.Behaviors.AllowInjectionScopeLocation = true;
    });

    Scope.Configure(_ => _.ExportInstance<ILog>(new Log("$")));

In activity:

public abstract class ScopedActivity : Activity
{
  [Import]
  public ILog Log { get; init; }
  
  protected override void OnCreate(Bundle? savedInstanceState)
  {
    var appScope = (Application as IScopedApplication)!.Scope;
    var childScope = appScope.CreateChildScope(_ =>
    {
      _.ExportFactory<ILog>(() =>
      {
        var appLog = appScope.Locate<ILog>();
        
        return appLog["activitities"][Class.SimpleName];
      });
    });
    var log = childScope.Locate<ILog>();
    childScope.Inject(this);   /// this.Log is different than log  (check scope)
  }
}

mcdis avatar Jan 17 '23 10:01 mcdis

Hi @mcdis,

I believe this is 'by-design'. I've checked the implementation of Inject extension method and here is what I've found:

image

Grace will get the top-most scope to perform property injection. So any changes in the child scopes won't take place.

Lex45x avatar Aug 14 '23 14:08 Lex45x