Register and Inject
Once upon a time, there was no Inject
and no Freeze
; Register
ruled the code.
Back then, there was a Register
overload defined thusly:
public static void Register<T>(this IFixture fixture, T item)
However, it had to share the API with this close relative:
public static void Register<T>(this IFixture fixture, Func<T> creator)
The creator of AutoFixture thought that this was good, but alas: users were stricken with confusion. Most grievously, a user could write:
fixture.Register(() => universe.LightUp());
but also
fixture.Register(universe.LightUp);
which means the exact same thing, because universe.LightUp
is a reference to a method, and thus matches a delegate.
However, that syntax looks like a property reference, so if LightUp
had been a property instead of a method, the first overload would be selected by the compiler.
This caused much confusion, so the Register<T>(this IFixture fixture, T item)
overload was renamed to Inject<T>(this IFixture fixture, T item)
.
Freeze
Freeze has a different history. A long time ago, when I still used AutoFixture in an imperative way, I noticed that I repeatedly wrote code like this:
var foo = fixture.Create<Foo>();
fixture.Inject(foo);
So I decided that this was a concept and named it Freeze. The Freeze
method is only shorthand for those two lines of code.
I'm looking for your help to understand the difference between Freeze, Inject, and also Register which, according to the source code, is just called by Inject method but it takes a lambda
In general, it shouldn't be too hard to distinguish between Inject
and Register
, since their signatures don't collide. Thus, if you try to accomplish a goal with one of those two methods, and your code compiles, you probably chose the right version.
This would also be the case for Freeze
if it wasn't for the overload used in the OP:
[EditorBrowsable(EditorBrowsableState.Never)]
public static T Freeze<T>(this IFixture fixture, T seed)
Notice that this overload actually has EditorBrowsableState.Never
, because it always confuses people. However, despite that, apparently people still find that overload, so I think it should be moved in AutoFixture 4. It's one of those features that exist because it was easy to implement...