views:

296

answers:

2

Any idea how I can tell AutoMapper to resolve a TypeConverter constructor argument using StructureMap?

ie. We have this:

    private class StringIdToContentProviderConverter : TypeConverter<string, ContentProvider> {
        private readonly IContentProviderRepository _repository;

        public StringIdToContentProviderConverter(IContentProviderRepository repository) {
            _repository = repository;
        }

        public StringIdToContentProviderConverter() {
            _repository = ObjectFactory.GetInstance<IContentProviderRepository>();
        }

        protected override ContentProvider ConvertCore(string contentProviderId) {
            return _repository.Get(new Guid(contentProviderId));
        }
    }

And in the AutoMap registration:

        Mapper.CreateMap<Guid, ContentProvider>().ConvertUsing<GuidToContentProviderConverter>();

However, I don't like the idea of hardwiring an ObjectFactory.GetInstance in my constructor for the converter. Any ideas how I can tell AutoMapper how to resolve my IContentProviderRepository?

Or ideas to other approaches for using Automapper to hydrate domain objects from viewmodel ID's using a repository?

+1  A: 

The ConstructUsing method seems to have an overload that accepts a Func<T1,T2> . In there you could access your container.

EDIT: Convert also knows such an overload such that you could do:

Mapper.CreateMap<A, B>().ConvertUsing(i=> c.With(i).GetInstance<B>());

Where c is your container

flq
Sorry, ContructUsing should be ConvertUsing
jacko
Thanks, this also works, but I think the accepted solution is cleaner
jacko
+4  A: 

We use this (in one of our Bootstrapper tasks)...

        private IContainer _container; //Structuremap container

        Mapper.Initialize(map =>
        {
            map.ConstructServicesUsing(_container.GetInstance);
            map.AddProfile<MyMapperProfile>();
        }
ozczecho
Cheers, perfect
jacko
It demands empty constructor. Isn't so?
Arnis L.
Hi Arnis, not sure what you mean? 'MyMapperProfile' just extends the Profile class as supplied by AutoMapper. We are telling AutoMapper what IoC container we are using.
ozczecho