My current project with assemblies for the domain model, MVC web application, and unit tests. How can I set up the AutoMapper configuration so that all assemblies reference the same configuration?
I would guess that I could put items in Global.asax for the web app, but how can I use that in the unit tests? Also, if the config is in Global.asax, will the domain model pick up the map?
Many thanks,
KevDog.
I tried the code above, but could not get it to work. I modified it a little bit as follows below. I think all that's left to do is to call it via a Bootstrapper from Global.asax. Hope this helps.
And I use it like this to associate a source with a destination pairing:
Then to Create the mappings automagically, I do this:
I have been moving my AutoMapper CreateMap calls into classes that live beside my view models. They implement an IAutomapperRegistrar interface. I use reflection to find the IAutoMapperRegistrar implementations, create an instance and add the registrations.
Here is the interface:
Here is an implementation of the interface:
Here is the code that performs the registrations in my Application_Start:
I figure it's appropriate and at least a bit logical; they are a lot easier to follow that way. Before I had hundreds of registrations in one huge bootstrap method and that was starting to become a pain in the ass.
Thoughts?
What we do is create a static class, something like BootStrapper, and put the initialization code in a static method in there. We're doing profiles, so you don't see much in there. Global.asax will call that at startup, domain will use it (since the configuration is singleton), and unit tests that need it call the BootStrapper.Configure() in their setup.
One final thing we do is keep a flag around on the bootstrapper, and set it to true when we configure. That way, configuration only executes once per AppDomain. That means once at startup of the global.asax (Application_Start), and once when we run unit tests.
HTH
I also use a bootstrapper to handle this sort of startup task thing. Actually, I use a chain of bootstrappers because I am crazy like that. Automapper-wise, we found it was alot cleaner to make some AutoMappingBuddy classes and decorate them with an attribute. We then wire up the mappers via some reflection calls (not cheap, but they only fire once at the get go). This solution was discovered after we got sick of finding an AutoMapper issue in line 841 of a 1200+ line file.
I thought about posting the code, but I can't really call it that purdy. Anyhow, here goes:
First, a simple interface for the AutoMappingBuddies:
Second, a little attribute to provide some glue:
Third, the AutoMappingEngine. It's where the magic happens:
Kinda slapped together in an hour or so, there are probably more elegant ways to get there.