DevTeam / Pure.DI

Pure DI for .NET
MIT License
410 stars 21 forks source link

Add some method to create a resolving context #17

Closed NikolayPianikov closed 1 year ago

NikolayPianikov commented 1 year ago

Scenario

Usage:

public static (T1, T2) Resolve<T1, T2>() =>
  ResolveInContext(() => ((T1)Resolver<T1>.Resolve(), (T2)Resolver<T2>.Resolve()))

Arguments must be taken into account. ResolveInContext should be private

johnjuuljensen commented 1 year ago

That would certainly work, but even just a generated DecreaseDepth method would be enough. The rest of the supporting code is trivial.

I tried out the concept and it works well

    // Could be generated for future-proofing
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    static void IncreaseDepth(ref int _deepness) {
        System.Threading.Interlocked.Increment(ref _deepness);
    }

    // Should be generated
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    static void DecreaseDepth(ref int _deepness) {
        if (System.Threading.Interlocked.Decrement(ref _deepness)==0) {
            _perResolveAppStartPure_DI_TTest_MultiResolveShared=default(AppStart.Pure_DI_TTest_MultiResolve.Shared?);
        }
    }

    sealed class ResolveScope<TRC>: IDisposable where TRC : class, IDisposable {
        public ResolveScope(TRC rc) {
            RC=rc;
            IncreaseDepth(ref _deepness);
        }

        public TRC RC { get; }

        public void Dispose() {
            DecreaseDepth(ref _deepness);
            RC.Dispose();
        }
    }

    public static (T1, T2) Resolve<T1, T2>(SharedArg sharedArg) {
        using ResolveScope<ResolveContext1> scope = new(new(sharedArg));
        return (
            (T1)Resolver<T1>.Resolve(),
            (T2)Resolver<T2>.Resolve()
        );
    }
NikolayPianikov commented 1 year ago

Please see the sample from description. NuGet