Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I initialize AutoMapper mappings in an Orchard module?

I am busy developing my first non-example Orchard module. It is a handful of controllers and views, with custom (EF) data access, and is largely independent of Orchard content types and parts. Normally I set up mappings in an Application_Start handler, but as the actions in this MVC module will be invoked in the context of the Orchard application, I no longer have that point of entry. My most obvious and immediate solution is to move mapping initialization into static constructors for mapped view models, e.g.

public class ApplicantPersonalDetailsModel : MappedViewModel<Applicant>
{
    static ApplicantPersonalDetailsModel()
    {
        Mapper.CreateMap<Applicant, ApplicantPersonalDetailsModel>().Bidirectional();
    }
    ....
}

How else can I do this? is there a better way to do this in MVC3/4 in general, or preferably, an event or hook I can grab in the Orchard application to also achieve this on applicaion startup?

like image 933
ProfK Avatar asked Dec 21 '12 06:12

ProfK


2 Answers

The way I have done it is by implementing IOrchardShellEvents

    public class MenuOrchardShellEvents : IOrchardShellEvents
    {
        public void Activated()
        {
            Mapper.CreateMap<YSRB.Menu.Models.Records.Customer, YSRB.Menu.Models.ViewModels.CustomerViewModel>()
                .ForMember(c => c.CustomerType, 
                    m => m.MapFrom(
                        x => (CustomerTypes)x.CustomerType
                    )
                );
            Mapper.CreateMap<YSRB.Menu.Models.ViewModels.CustomerViewModel, YSRB.Menu.Models.Records.Customer>()
                .ForMember(c => c.CustomerType,
                    m => m.MapFrom(
                        x => (int)x.CustomerType
                    )
                );
        }

        public void Terminating()
        {
            //Do nothing
        }
    }

Hope this helps.

like image 187
ysrb Avatar answered Oct 20 '22 11:10

ysrb


The Handler is the best place for initializing your variables, even if you haven't defined any part inside your module you can define one without a driver but with handler.

public class InitPartHandler : ContentHandler
{
    public InitPartHandler(IRepository<InitPartRecord> repository)
    {
         OnInitializing<InitPart>((context, part) =>
                 // do your initialization here
            );
    }
}

EDIT

InitPart and InitPartRecord would be  

public class InitPart : ContentPart<InitPartRecord>
{

}

public class InitPartRecord : ContentPartRecord
{

}
like image 37
Behnam Esmaili Avatar answered Oct 20 '22 11:10

Behnam Esmaili