Your first step is to tell AutoMapper to tie into dependency resolution for service construction. You can do that in MVC with something like this:
AutoMapper.Mapper.Configuration.ConstructServicesUsing(
t => DependencyResolver.Current.GetService(t));
Next, construct your custom value resolvers and so forth using base classes or interfaces so they can be injected.
public abstract class FormattingResolver : IValueResolver
{
public ResolutionResult Resolve(ResolutionResult source)
{
return source.New(this.Format(source.Value.ToString()));
}
public abstract string Format(string input);
}
public class DefaultFormatter : FormattingResolver
{
public override string Format(string input)
{
return input + "Default";
}
}
public class Tenant1Formatter : FormattingResolver
{
public override string Format(string input)
{
return input + "Tenant 1";
}
}
Now register those value resolvers using Autofac and the multitenant support.
var builder = new ContainerBuilder();
// Register the default in the app container
builder.RegisterType<DefaultFormatter>().As<FormattingResolver>();
var container = builder.Build();
var mtc = new MultitenantContainer(new TenantIdStrategy(), container);
// Register the tenant override
mtc.ConfigureTenant(
'Tenant1',
b => b.RegisterType<Tenant1Formatter>().As<FormattingResolver>());
// Make sure the dependency resolver is multitenant
var resolver = new AutofacDependencyResolver(mtc);
DependencyResolver.SetResolver(resolver);
When you register your AutoMapper mappings, make sure to use the base class rather than the specific class for the custom value resolver.
Mapper.CreateMap<DataModel, ViewModel>()
.ForMember(d => d.DisplayName,
opt => opt.ResolveUsing<FormattingResolver>());
Now when AutoMapper executes the mapping operation, it will get the custom value resolver by calling DependencyResolver.Current.GetService
and the Autofac multitenant container will return the appropriate resolver for the tenant. The mapping will use the specific tenant's custom value resolver, which means the override formatting will take place as expected.
I have this working in a couple of my own applications and it works great.