Although it’s pretty self-explanatory, I thought that some simple instructions how to use the Unity Automapper might be a good idea anyway.
If you’re reading this, there’s a good chance you’re coming here from the link in NuGet’s description, in which case you can skip straight to the Usage section below. Otherwise, read on…
- Fire up Visual Studio and open your solution.
- Open NuGet on the project you wish to perform the Unity registrations on (typically this will be your startup project)
- Search for Unity Automapper. NuGet isn’t the best at finding packages so you might have to search for it a bit.
- Alternatively you can simply install it via the Package Manager Console with the command.
- That’s it! You’re now ready to start using the AutoMapper!
This is even easier.
- Add a using statement to the top of your source file where you want to perform the registration on.
- Create your Unity Container as normal.
- If you have a list of types at compile-time that you wish to use as the source of registrations, simply call the AutomapTypes() method: –
- Alternatively you could just chuck in all the types in e.g. your executing assembly at run-time: –
- If, on the other hand you’re using a more plug-in style architecture where e.g. you want to source your registrations from assemblies that your registration project doesn’t have a reference to, or you want to map concretes that are internal to another assembly etc., you can just provide the assembly names using the AutomapAssemblies() method: –
- So in this example, perhaps we have an interface in our Services assembly e.g. IDataAccess, which is implemented by a class in DataAccess. You can now make the concrete implementation completely private; it’ll simply be found by the mapper and wired up.
That’s it! Either of those calls will perform any mappings that it can find into Unity; you’re now ready to go.
Here are a few other features that the mapper offers…
- If you want to make your data access layer a singleton in Unity, simply mark the interface (not the implementation!) with the [Singleton] attribute (this necessitates referencing the Automapper from that assembly as well).
- If you want to specifically ignore a type from the Automapper – perhaps you have a fake class you sometimes turn on or use in testing etc. rather than when really running – just mark it with the [DoNotMap] attribute.
That’s pretty much it. Two method calls and two (optional) attributes – not a massive API but hopefully one that saves you some time when using Unity.