Reputation: 1581
I have the following custom value resolver:
public class ImageUrlResolver<T> : ValueResolver<T, string>
{
private readonly ISettings _settings;
public ImageUrlResolver(string size)
{
_settings = ObjectFactory.GetInstance<ISettings>();
}
...
}
.ForMember(d => d.ImageUrl,
o => o.ResolveUsing<ImageUrlResolver>().ConstructedBy(() => new ImageUrlResolver("150x150"))
I'm trying to update it so that I can inject StructureMap's IContainer
instead of using ObjectFactory
, but I'm not sure how I can construct the resolver when it has constructor arguments. Is there anything else I can do?
Upvotes: 3
Views: 4369
Reputation: 1581
I've figured out a solution. I'm now injecting IContainer
into the profile, and passing it through to the resolver.
public static void Initialise(IContainer container)
{
var type = typeof(Profile);
var profiles = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(t => type.IsAssignableFrom(t) && type != t)
.Select(container.GetInstance)
.Cast<Profile>()
.ToList();
Mapper.Initialize(c =>
{
profiles.ForEach(c.AddProfile);
c.ConstructServicesUsing(container.GetInstance);
});
}
public class MyProfile : Profile
{
private readonly IContainer _container;
public MyProfile(IContainer container)
{
_container = container;
}
private static void Configure()
{
Mapper.CreateMap<Entity, Model>()
.ForMember(d => d.ImageUrl, o => o.ResolveUsing<ImageUrlResolver>().ConstructedBy(() => new ImageUrlResolver(_container, "150x150"))
}
}
Maybe not the cleanest solution, but it's the only one I found that works.
Upvotes: 1