无法在AutoFac中注册ITypeConverter

时间:2019-07-01 07:41:06

标签: c# .net automapper autofac core

我在.Net Core 2.2中创建了WebApi。我需要使用AutoFac和Automapper。我想编写一个动作,在Dto中创建时将一个属性从int转换为object。

转换器看起来像这样:

public class IntToOfferPlaceConverter : ITypeConverter<int, OfferPlace>
    {
        private readonly IOfferPlaceLogic _logic;

        public IntToOfferPlaceConverter(IOfferPlaceLogic logic)
        {
            _logic = logic;
        }

        public OfferPlace Convert(int source, OfferPlace destination, ResolutionContext context)
        {
            var offerPlaceResult = _logic.GetById(source);
            if (offerPlaceResult.Success == false)
            {
                return null;
            }

            return offerPlaceResult.Value;
        }
    }

AutoMapper中的产品:

        public FileProfile()
        {
            CreateMap<FileDto, File>();

            CreateMap<int, OfferPlace>()
                .ConvertUsing<IntToOfferPlaceConverter>();
        }

Autofac中的模块:

        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
                .AsClosedTypesOf(typeof(ITypeConverter<,>))
                .AsSelf();
        }

发生映射时,会发生这样的错误:

MissingMethodException: No parameterless constructor defined for this object.
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, bool publicOnly, bool wrapExceptions, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor)

AutoMapperMappingException: Error mapping types.

Mapping types:
FileDto -> File
GrillBer.WebApi.Dto.FileDto -> GrillBer.Models.File

Type Map configuration:
FileDto -> File
GrillBer.WebApi.Dto.FileDto -> GrillBer.Models.File

Destination Member:
OfferPlace

问题出在构造函数上,但是它在autofac中注册。我在哪里犯错?

0 个答案:

没有答案