autofac / Autofac

An addictive .NET IoC container
https://autofac.org
MIT License
4.44k stars 836 forks source link

Please teach AutoFac about Immutable Collections #1372

Closed TonyValenti closed 5 months ago

TonyValenti commented 1 year ago

Problem Statement

We have code like this:

public class Foo {
  protected ImmutableArray<Bar> Data {get; }

  public Foo(IEnumerable<Bar> Data){ 
    this.Data = Data.ToImmutableArray();
  }
}

And we'd like to replace it with code like this:

public class Foo {
  public required ImmutableArray<Bar> Data {protected get; init; }
}

But Autofac does not know how to construct an ImmutableArray or ImmutableList.

Desired Solution

Please teach Autofac how to construct those types as a replacement for IEnumerable.

Alternatives You've Considered

I could do this:

public class Foo {
  public required IEnumerable<Bar> Data {protected get; init; }
}

But it does not have the same characteristics as Immutables.

alistairjevans commented 1 year ago

Is there a reason you cannot use IReadOnlyList<Bar>?

public class Foo {
  public required IReadOnlyList<Bar> Data {protected get; init; }
}

That works out-of-the-box, and provides most of the same semantics as immutable data structures provided you don't reflect over the underlying structure.

TonyValenti commented 1 year ago

@alistairjevans With the immutable structures I get non-destructive mutations which I don't get with the IReadOnlyList. IReadOnlyList is basically only a pre-enumerated enumerable.

alistairjevans commented 1 year ago

Are you modifying lists of injected services after they are injected? You might have to provide a fuller example here, not sure I understand.

TonyValenti commented 1 year ago

Hi @alistairjevans - No, we're not doing any modifications to them. We just prefer using ImmutableArray/ImmutableList over IReadOnlyCollection.

tillig commented 5 months ago

Duplicate #1408