I am configuring Automapper in the Bootstrapper and I call the Bootstrap() in the Application_Start(), and I’ve been told that this is wrong because I have to modify my Bootstrapper class each time I have to add a new mapping, so I am violating the Open-Closed Principle.
How do you think, do I really violate this principle?
public static class Bootstrapper
{
public static void BootStrap()
{
ModelBinders.Binders.DefaultBinder = new MyModelBinder();
InputBuilder.BootStrap();
ConfigureAutoMapper();
}
public static void ConfigureAutoMapper()
{
Mapper.CreateMap<User, UserDisplay>()
.ForMember(o => o.UserRolesDescription,
opt => opt.ResolveUsing<RoleValueResolver>());
Mapper.CreateMap<Organisation, OrganisationDisplay>();
Mapper.CreateMap<Organisation, OrganisationOpenDisplay>();
Mapper.CreateMap<OrganisationAddress, OrganisationAddressDisplay>();
}
}
I would argue that you are violating two principles: the single responsibility principle (SRP) and the open/closed principle (OCP).
You are violating the SRP because the bootstrapping class have more than one reason to change: if you alter model binding or the auto mapper configuration.
You would be violating the OCP if you were to add additional bootstrapping code for configuring another sub-component of the system.
How I usually handle this is that I define the following interface.
For each component in the system that needs bootstrapping I would create a class that implements that interface.
I use Ninject to inject the dependencies.
IConfigurationis the underlying implementation of the staticAutoMapperclass andModelBinderDictionaryis theModelBinders.Binderobject. I would then define aNinjectModulethat would scan the specified assembly for any class that implements theIGlobalConfigurationinterface and add those classes to a composite.I would then add the following code to the Global.asax file.
Now my bootstrapping code adheres to both SRP and OCP. I can easily add additional bootstrapping code by creating a class that implements the
IGlobalConfigurationinterface and my global configuration classes only have one reason to change.