Extension point to wire in domain data #523
Replies: 1 comment
-
Hi. Thank you for the post. You'll have to explain the "
This means that I agree, the two extra I think, ideally, a C# extension property would work best here; but C# extension properties aren't a thing yet. 😭 So, the next best thing, alternatively, might be to add a dedicated void Main()
{
var faker = new Faker<MyDomainObject>()
.RuleFor(x => x.SpecialValue, fd => fd.Domain.SpecialString());
faker.Generate().Dump();
}
public class MyDomainObject
{
public string SpecialValue;
}
public static class ExtensionsForDomainFakerT
{
public static Faker<T> RuleFor<T, TProperty>(this Faker<T> fakerT, Expression<Func<T, TProperty>> property, Func<FakerWithDomain, TProperty> setter)
where T : class
{
return fakerT
.RuleFor(property, f =>
{
var domainFaker = new FakerWithDomain(f);
return setter(domainFaker);
});
}
}
public class FakerWithDomain : Faker
{
public FakerWithDomain(Faker existing) : base()
{
this.Domain = this.Notifier.Flow(new DomainDataSet());
this.Random = existing.Random;
}
public DomainDataSet Domain { get; init; }
}
public class DomainDataSet : Bogus.DataSet
{
public string SpecialString()
{
var value = this.Random.Replace("???###");
return value;
}
} The above code seems to work on the .NET 8 SDK. It's a bit verbose to get the " If not, try changing There are probably a few ways to hack it with the DLR (dynamic language runtime and the Feel free to carry on the discussion after I close the thread. Hope that helps, |
Beta Was this translation helpful? Give feedback.
-
Hi there,
When I am generating generic data (people, addresses, etc.), Bogus has the really lovely fluent syntax with the
DataSets
as properties. Now, I usually create my own methods to create bogus instances of simple domain concepts, say, myid
s are all 8 digit hexadecimal, so I have aCreateId(Faker faker)
method, that uses the supplied faker to generate just that without me having to express that same rule everywhere I see anId
property.In order to wire that in, I either have a
DomainFaker
static class, and I do something like.RuleFor(x => x.Id, f => DomainFaker.Id(f))
, or I create an instance class and extension method onFaker
that returns me that instance class (passing along the faker instance), something like.RuleFor(x => x.Id, f => f.Domain().Id()
. However, the extra pair of brackets afterDomain
sort of bugs me as idiosyncratic as none of the actualDataSet
s needs that.Would it be possible to extend
Faker
with an "empty"Domain
(partial?) class that people could use to add their extension methods to? ("Empty" as in it would probably need a property that references back the originalFaker
in order to have that available in the extension methods. Making it partial would probably allow for better extensibility.) That way we could do something like.RuleFor(x => x.Id, f => f.Domain.Id()
.Cheers, and thanks for the awesome package!
Beta Was this translation helpful? Give feedback.
All reactions