配置AutoMapper以实现ITypeConverter<> Autofac的构造函数依赖 [英] Configuring AutoMapper to fulfil ITypeConverter<,> constructor dependecies with Autofac

查看:216
本文介绍了配置AutoMapper以实现ITypeConverter<> Autofac的构造函数依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次使用Autofac将AutoMapper的IMapper接口注入到具有对象映射要求的类中.我已经取得了一些进展,有了一点帮助,添加了各种依赖项使用程序集扫描访问AutoMapper的寄存器:

My first time working with Autofac to inject AutoMapper's IMapper interface into classes that have an object mapping requirement. I have made some progress, with a little help, getting the various dependencies added to AutoMapper's register using Assembly Scanning:

builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
    .AsClosedTypesOf(typeof(ITypeConverter<,>))
    .AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof(AutoMapperExtensions).Assembly)
    .AssignableTo<Profile>().As<Profile>();

builder.Register(context => {
    var profiles = context.Resolve<IEnumerable<Profile>>();
    return new MapperConfiguration(x => {
        foreach (var profile in profiles) x.AddProfile(profile);
    });
}).SingleInstance().AutoActivate().AsSelf();

builder.Register(context => {
    var componentContext = context.Resolve<IComponentContext>();
    var config = componentContext.Resolve<MapperConfiguration>();
    return config.CreateMapper();
}).As<IMapper>();

这对于没有任何注入依赖项的ITypeConverter<,>非常适用:

This works perfectly for an ITypeConverter<,> that doesn't have any injected dependencies:

public class SourceToDestinationTypeConverter : ITypeConverter<SourceModel, DestinationModel> {
    public DestinationModel Convert(SourceModel source, DestinationModel destination, ResolutionContext context) {
        if (source.Items == null) {
            return null;
        }

        return new DestinationModel {
            FirstItem = source.Items.FirstOrDefault(),
            LastItem = source.Items.LastOrDefault()
        };
    }
}

但是从我添加一个依赖关系的那一刻起,在这个人为的示例中,就是一个验证器:

However from the moment I add a dependency, in this contrived example, a validator:

public class SourceToDestinationTypeConverter : ITypeConverter<SourceModel, DestinationModel> {
    private readonly IValidator<SourceModel> _validator;

    public SourceToDestinationTypeConverter(IValidator<SourceModel> validator) {
        _validator = validator;
    }

    public DestinationModel Convert(SourceModel source, DestinationModel destination, ResolutionContext context) {
        if (!_validator.Validate(source)) return null;

        return new DestinationModel {
            FirstItem = source.Items.FirstOrDefault(),
            LastItem = source.Items.LastOrDefault()
        };
    }
}

引发以下异常:

Application.TypeConverters.SourceToDestinationTypeConverter需要具有0个args或仅可选args的构造函数

Application.TypeConverters.SourceToDestinationTypeConverter needs to have a constructor with 0 args or only optional args

在我看来,AutoMapper 需要被告知使用Autofac 来实现依赖关系.但是,我还无法找到如何告诉它这样做的方法.

It seems clear to me that AutoMapper needs to be told to use Autofac to fulfil the dependencies. However, I haven't been able to find out how to tell it to do so.

如果需要进一步澄清错误,则完整的解决方案是可在GitHub上获得.

The full solution is available on GitHub if further clarification of the error is required.

推荐答案

我猜你忘记了

I'm guessing you forgot to add the call to ConstructServicesUsing during AutoMapper configuration. Make sure to do this

确切地如何将Autofac与您的应用程序集成真正取决于您拥有哪种类型的应用程序(Windows Service?MVC?Web API?Windows Forms?UAP?)以及您对整个生命周期范围使用的期望是.您的问题中未包含任何内容.但是,如果您在网络上搜索"autofac constructservicesusing",则会提供大量示例,其中包括关于同一主题的其他几个StackOverflow问题.

Exactly how to integrate Autofac with your app really depends on what kind of app you have (Windows Service? MVC? Web API? Windows Forms? UAP?) and what your expectations around lifetime scope usage are. None of that was included in your question. However, if you search the web for "autofac constructservicesusing" you come up with plenty of examples including several other StackOverflow questions on the same topic.

这是一个简单的示例,显示了很多内容如果您使用的是MVC或Web API应用,并且需要每个请求范围的支持,请

Here's a simple example that shows pretty much exactly what you're doing. If you're using an MVC or Web API app and need per-request-scope support, I have a full blog walkthrough on that.

通过注释的方式,我不确定AutoActivate调用是否确实必要. SingleInstance是线程安全的,并且懒惰地构建AutoMapper配置文件实际上并不需要花费很长时间.您可能要尝试不使用它,特别是如果AutoMapper本身直到AutoActivate运行之后才执行该部分.

By way of a note, I'm not sure if the AutoActivate call is really necessary. SingleInstance is thread-safe and it doesn't actually take that long to build an AutoMapper profile lazily. You may want to try without it, especially if AutoMapper itself isn't executing that part until after AutoActivate has run.

这篇关于配置AutoMapper以实现ITypeConverter&lt;&gt; Autofac的构造函数依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆