Customize key generation for dictionaries

Feb 29, 2012 at 7:07 AM

I'm looking for a way to customize the generation of keys for a dictionary.

class Foo
  public IDictionary<int, Bar> Bars { get;set; }
class Bar
  public int Id {get;set;}
I want to use the Id property of the Bar class as the key for the dictionary and the instances of Bar should be created by AutoFixture.

Feb 29, 2012 at 3:28 PM

You can customize your Fixture instance like this: 

fixture.Register<IDictionary<int, Bar>>(() =>
    fixture.CreateMany<Bar>().ToDictionary(b =>

 However, whenever one encounters friction like this, it's time to evaluate whether the API could be improved.

Right now, it's possible to do things like this:

foo.Bars[1].Id = 2;

That's probably not what you want. Is there any particular reason why you want to expose the Bar instances as a dictionary? Why not instead a KeyedCollection? Or, my personal favorite, IEnumerable<Bar>. A simple Where method can give you a Bar instance with a particular Id.

Mar 1, 2012 at 6:52 AM


I played with FromFactory but Register looks much cleaner.

As to the re-design of the data classes: I'm totally with you and it's already been on my list of proposals for a while. Unfortunately that's a rather long list ...