Luke Warren Dev
Software Development Tips and Stories When I feel Like It

Introducing the Model Builder - You Don't Need Automapper

This post is quite simple. You don't need Automapper, all you need is a model builder.

,
Categories: .NET , C#
Tags: .NET , C# , tips , modelbuilder , automapper
Introducing the Model Builder - You Don't Need Automapper

Now I am a big fan of "don't reinvent the wheel" but at times we as developers need to learn where to draw the line. In this article I will show you a very simple pattern that gives you more control and avoids needing to bring in yet another dependency - AutoMapper.

Disclaimer: I like and use Automapper in many of my projects and will continue to. It is a great library but sometimes you just don't need it.

Example ModelBuilder

All our model builder class does is either create a Model class from its entity/domain class equivalent OR parse a Model class back to a entity/domain class.

public class ModelBuilder
{
    public ProvinceModel Create(Province province)
    {
        Require.NotNull(province);
        Require.NotNullOrEmptyOrWhitespace(province.Name);

        return new ProvinceModel
        {
            Id = province.Id,
            Name = province.Name
        };
    }

    public Province Parse(ProvinceModel model)
    {
        Require.NotNull(model);
        Require.NotNullOrEmptyOrWhitespace(model.Name);

        return new Province
        {
            Id = model.Id,
            Name = model.Name
        };
    }
}

Wondering what that Require stuff is? Those are just some handy methods contained in the Rework Nuget Package (yes, this is a shameless plug).

ModelBuilder In Action:

I usually either inject my model builder in the constructor for the class that needs to use it, or just instantiate it right there in the constructor. The later does make it a concrete dependency rather than an abstraction but sometimes this makes sense IMO.

You could, either create a model builder for each entity-domain relationship you have or just put them all in one. You are reading this blog so I will assume that you are smart and can figure out what you prefer ;).

For completeness, here is how you actually use the thing:

    public ProvinceController(IProvinceService service)
    {
        // Init my service and create my model builder
        _service = service;
        _builder = new ModelBuilder();
    }

   public object Post(ProvinceModel model)
    {
        Province province = _builder.Parse(model);
        _provinceService.Create(province); // My "service" is creating the province in the DB
        return _builder.Create(province);
    }

comments powered by Disqus