Bogus icon indicating copy to clipboard operation
Bogus copied to clipboard

Binder throw ambiguous match exception for object with read only indexer property that has two implementations in base class

Open AlesDo opened this issue 2 years ago • 2 comments

Version Information

Software Version(s)
Bogus NuGet Package 34.0.2
.NET Core? 7.0.11
.NET Full Framework?
Windows OS? 11 Pro 22621.2283
Linux OS?
Visual Studio? 17.8.0 Preview 2.0

What locale are you using with Bogus?

en

What is the expected behavior?

Should not throw exception when enumerating properties.

What is the actual behavior?

System.Reflection.AmbiguousMatchException is thrown

Please provide a stack trace.

at System.RuntimeType.GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)

Any possible solutions?

Yes it is possible to ignore the indexer properties where the check for parent class properties is performed. Have created a branch in my fork with a unit test and a possible solution.

How do you reproduce the issue?

By using fluent syntax with an object that has two read only indexers that are defined in a base class. Have created a branch in my fork with a unit test and a possible solution.

Do you have a unit test that can demonstrate the bug?

Yes. Have created a branch in my fork with a unit test and a possible solution.

Can you identify the location in Bogus' source code where the problem exists?

Yes. Binder.cs line 114. Because both indexers have same default name Item resolving PropertyInfo by name fails.

If the bug is confirmed, would you be willing to submit a PR?

Yes.

AlesDo avatar Sep 28 '23 20:09 AlesDo

I've run into this bug just this week and am curious if there's intent on a fix in an upcoming release? I can work around by adding a protected set; to the property, but would love to not have to do this as it reduces the integrity of the instantiated class.

addixon-cnhi avatar Apr 16 '24 19:04 addixon-cnhi

@addixon-cnhi I haven't dived into this particular issue yet, but I suspect one workaround might be to create your own Binder:

  • https://github.com/bchavez/Bogus/blob/0f4efc216b9a024d8a6c10c3d106980ff61ce927/Source/Bogus/Binder.cs

The Binder is responsible for reflecting over / introspection of T in Faker<T> to determine what properties/fields are available on T. Also, the original post has a branch with some of the changes that seem to have worked around the original issue.

You can supply your custom Binder here in new Faker<T>(binder: MyCustomBinder):

  • https://github.com/bchavez/Bogus/blob/0f4efc216b9a024d8a6c10c3d106980ff61ce927/Source/Bogus/Faker%5BT%5D.cs#L147

Let me know if that helps.

bchavez avatar Apr 16 '24 22:04 bchavez