Asp.net web api 使用AutoMapper和AutoFac IOC将DTO中的外键ID映射到对象

Asp.net web api 使用AutoMapper和AutoFac IOC将DTO中的外键ID映射到对象,asp.net-web-api,automapper,autofac,Asp.net Web Api,Automapper,Autofac,我是我的Web API项目,我正在尝试将DTO调用中的id映射到对象。但我在使用AutoFac设置dependecy时遇到了一些问题 下面是我正在使用的类 public abstract class DomainObject<IdT> : IDomainObject<IdT> { public virtual IdT Id { get; set; } } public class Course : DomainObject<long> {

我是我的Web API项目,我正在尝试将DTO调用中的id映射到对象。但我在使用AutoFac设置dependecy时遇到了一些问题

下面是我正在使用的类

public abstract class DomainObject<IdT> : IDomainObject<IdT> 
{
    public virtual IdT Id { get; set; }
}


public class Course : DomainObject<long>
{
    public string CourseName { get; set; }
    public Teacher Teacher { get; set; }
}

public class  Teacher : DomainObject<long>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
下面是实体转换器

 public class EntityConverter<T,IdT> : ITypeConverter<IdT, T>
 {
    private readonly IGenericRepository<T, IdT> _repository;
    public EntityConverter(IGenericRepository<T, IdT> repository)
    {
        _repository = repository;
    }
    public T Convert(ResolutionContext context)
    {
        return _repository.GetById((IdT)context.SourceValue);
    }
 }
公共类EntityConverter:ITypeConverter
{
专用只读IGenericRepository存储库;
公共实体转换程序(IGenericRepository repository repository repository repository)
{
_存储库=存储库;
}
公共T转换(ResolutionContext上下文)
{
return _repository.GetById((IdT)context.SourceValue);
}
}

如何使用AutoFac定义映射并注入依赖项。

从您的问题中不清楚您遇到了什么问题。如果您只是试图将TeacherId映射到DTO中,那么根本没有工作要做:

Mapper.CreateMap<Course, CourseDTO>();

如果您试图做比这更复杂的事情,那么您需要发布您试图映射到的实际DTO。

您希望注入哪种类型?在哪里?@Cyril Durand-请参考帖子。我正试图通过温莎城堡的autofac安装来实现这一点
Mapper.CreateMap<Course, CourseDTO>();
ContainerBuilder builder = new ContainerBuilder();
var container = builder.Build();
Mapper.Initialize(cfg => cfg.ConstructServicesUsing(container.Resolve));