简体   繁体   English

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

[英]Using dependency injection with AutoMapper ValueResolver that has constructor arguments

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.我正在尝试更新它,以便我可以注入 StructureMap 的IContainer而不是使用ObjectFactory ,但是我不确定当它具有构造函数参数时如何构造解析器。 Is there anything else I can do?还有什么我可以做的吗?

I've figured out a solution.我想出了一个解决办法。 I'm now injecting IContainer into the profile, and passing it through to the resolver.我现在将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"))
    }
}

Maybe not the cleanest solution, but it's the only one I found that works.也许不是最干净的解决方案,但它是我发现唯一有效的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM