M
M
marshinov2013-10-24 19:42:31
Problem-Based Design
marshinov, 2013-10-24 19:42:31

auto mapper. Mapping from DTO/ViewModel to Domain.Entity

I try not to create ViewModels and DTOs while possible. But it happens that you need to give only the id, and not the whole entity, for example, there is a Product, the Product has a Category. And we want to give JSON in which there will be just CategoryId. Everything is clear here, just map Product.Category.Id -> to productDto.categoryId.

The opposite situation: we get the same productDto. Creating a reverse mapping is not hard, but I haven't found a way to inject dependencies into resolve methods. In the best case, I can create my own TypeResolver, but still I have to reach for some static method inside to get the UoW. And this will turn into problems for me in the test code. with database objects. Of course, you can ignore all properties with Domain.Entity in paming from DTO to Domain and set them manually, but this is no longer so elegant and you can forget something, while AutoMapper will not let you forget, thanks to AssertConfigurationIsValid.

Is it really impossible to inject dependencies beautifully in this case, or have I missed something?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Timur Rakhmatillaev, 2013-10-25
@marshinov

Here's a method I've had to use on projects at ByndyuSoft, and one that I highly recommend for sticky situations like this.
1. Create a public property in your profiles in which you need to access the database and which will contain a link to the TypeResolver abstract factory.
2. Register all Profiles in the IoC container for your type (almost all mainstream containers support this, we use Castle.Windsor).
3. Register your abstract factory.
4. Create all profiles using IoC resolution and register them. To register profiles, I recommend using my NArms.Automapper library (available in NuGet), but you can do it manually.
5. In the profile, simply create the required TypeResolver using the abstract factory.
If Castle.Windsor is used, then you can resort to a less flexible, but still viable solution using NArms.Windsor. Static IoC class thus can be initialized, let's say in one of the Installers (I'm getting a special WindsorInstaller for this case). In this case, you can resolve anything via IoC.Resolve<>(). The method is not very beautiful, and you get that. extra dependency in builds with profiles (from Castle.Windsor).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question