Created
February 8, 2013 02:53
-
-
Save crmckenzie/4736254 to your computer and use it in GitHub Desktop.
Demo of a fluent api implementation for mapping one object to another. The unit test does not actually exercise the implementation, but it does demonstrate how the api will look to the consumer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Test] | |
public void ApiDocumentation() | |
{ | |
// Arrange | |
var builder = Substitute.For<IBuilder>(); | |
builder.Create<string>().From(5.0m).Returns("Five"); | |
// Act | |
var result = builder.Create<string>().From(5.0m); | |
// Assert | |
Assert.That(result, Is.EqualTo("Five")); | |
} | |
public interface IBuilder | |
{ | |
IBuilderNode<TOutput> Create<TOutput>(); | |
} | |
public interface IBuilderNode<out TOutput> | |
{ | |
TOutput From<TInput>(TInput input); | |
} | |
public interface IBuild<in TInput, out TOutput> | |
{ | |
TOutput Build(TInput input); | |
} | |
/// <summary> | |
/// Implement using your favorite Dependency Injection framework. | |
/// </summary> | |
public interface IBuildProvider | |
{ | |
IBuild<TInput, TOutput> Get<TInput, TOutput>(); | |
} | |
public class Builder : IBuilder | |
{ | |
private readonly IBuildProvider _buildProvider; | |
public IBuilderNode<TOutput> Create<TOutput>() | |
{ | |
return new BuilderNode<TOutput>(_buildProvider); | |
} | |
public Builder(IBuildProvider buildProvider) | |
{ | |
_buildProvider = buildProvider; | |
} | |
} | |
public class BuilderNode<TOutput> : IBuilderNode<TOutput> | |
{ | |
private readonly IBuildProvider _buildProvider; | |
public TOutput From<TInput>(TInput input) | |
{ | |
var builder = _buildProvider.Get<TInput, TOutput>(); | |
var result = builder.Build(input); | |
return result; | |
} | |
public BuilderNode(IBuildProvider buildProvider) | |
{ | |
_buildProvider = buildProvider; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment