将依赖注入与具有构造函数参数的 AutoMapper ValueResolver 结合使用

Using dependency injection with AutoMapper ValueResolver that has constructor arguments

我有以下自定义值解析器:

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"))

我正在尝试更新它,以便我可以注入 StructureMap 的 IContainer 而不是使用 ObjectFactory,但我不确定当解析器具有构造函数参数时如何构造解析器。还有什么我可以做的吗?

我找到了解决办法。我现在将 IContainer 注入配置文件,并将其传递给解析器。

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"))
    }
}

也许不是最干净的解决方案,但这是我发现的唯一可行的解​​决方案。