Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject AutoMapper

I have been working on injecting AutoMapper into controllers. I like the implementation of Code Camp Server. It creates a wrapper around AutoMapper's IMappingEngine. The dependency injection is done using StructureMap. But I need to use Castle Windsor for my project. So, how do we implement the following dependency injection and set-up using Windsor? I am not looking for line-by-line equivalent implementation in Castle Windsor. If you want to do that, please feel free. Instead, what is Windsor equivalent of StructureMap's Registry and Profile? I need Profile to define CreateMap<> like the following.

Thanks.

Meeting controller:

public MeetingController(IMeetingMapper meetingMapper, ...)

Meeting Mapper:

public class MeetingMapper : IMeetingMapper
{

    private readonly IMappingEngine _mappingEngine;

    public MeetingMapper(IMappingEngine mappingEngine)
    {
      _mappingEngine = mappingEngine;
    }

    public MeetingInput Map(Meeting model)
    {
        return _mappingEngine.Map<Meeting, MeetingInput>(model);    
    }

    ......
}

Auto Mapper Registry:

public class AutoMapperRegistry : Registry
{

    public AutoMapperRegistry()
    {
        ForRequestedType<IMappingEngine>().TheDefault.Is.ConstructedBy(() => Mapper.Engine);
    }
}

Meeting Mapper Profile:

public class MeetingMapperProfile : Profile
{

    public static Func<Type, object> CreateDependencyCallback = (type) => Activator.CreateInstance(type);

    public T CreateDependency<T>()
    {
        return (T)CreateDependencyCallback(typeof(T));
    }

    protected override void Configure()
    {
        Mapper.CreateMap<MeetingInput, Meeting>().ConstructUsing(
            input => CreateDependency<IMeetingRepository>().GetById(input.Id) ?? new Meeting())

       .ForMember(x => x.UserGroup, o => o.MapFrom(x => x.UserGroupId))
       .ForMember(x => x.Address, o => o.Ignore())
       .ForMember(x => x.City, o => o.Ignore())
       .ForMember(x => x.Region, o => o.Ignore())
       .ForMember(x => x.PostalCode, o => o.Ignore())
       .ForMember(x => x.ChangeAuditInfo, o => o.Ignore());
    }
}
like image 566
Roger Avatar asked Nov 12 '09 03:11

Roger


People also ask

When should you not use AutoMapper?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.

What is AutoMapper good for?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.

How does AutoMapper work internally?

How AutoMapper works? AutoMapper internally uses a great concept of programming called Reflection. Reflection in C# is used to retrieve metadata on types at runtime. With the help of Reflection, we can dynamically get a type of existing objects and invoke its methods or access its fields and properties.


2 Answers

you mean how do you register it in Windsor?

you may have to register FactorySupportFacility fist... I have no way of checking at this moment.

container.AddFacility<FactorySupportFacility>();

and then

container.Register(Component.For<IMappingEngine>().UsingFactoryMethod(()=>
            Mapper.Engine));
like image 167
Krzysztof Kozmic Avatar answered Jan 02 '23 18:01

Krzysztof Kozmic


I'm not familiar with Castle Windsor but here is the StructureMap syntax. You would need to set up your registry a little different. Instead of setting the IMappingEngine to Mapper.Engine, you will have to do configure a few more interfaces. It's a little more work but this will allow you to set the profile as part of registration.

public AutoMapperRegistry()
{
    //type mapping
    For<ConfigurationStore>()
        .Singleton()
        .Use(ctx =>
        {
            ITypeMapFactory factory = ctx.GetInstance<ITypeMapFactory>();
            ConfigurationStore store 
                = new ConfigurationStore(factory, MapperRegistry.AllMappers());
            IConfiguration cfg = store;
            //Here's where you load your profile
            cfg.AddProfile<MeetingMapperProfile>();
            store.AssertConfigurationIsValid();
            return store;
        });
    For<IConfigurationProvider>().Use(ctx => ctx.GetInstance<ConfigurationStore>());
    For<IConfiguration>().Use(ctx => ctx.GetInstance<ConfigurationStore>());
    For<IMappingEngine>().Use<MappingEngine>();
    For<ITypeMapFactory>().Use<TypeMapFactory>();
}
like image 26
Jay Walker Avatar answered Jan 02 '23 18:01

Jay Walker