如何将自动映射器直接注入到控制器下方的存储库层

时间:2018-11-28 18:14:07

标签: c# asp.net-core automapper

这是一个ASP.net Core 2.1项目。

如何将Auto Mapper直接注入存储库层?当前,我已经将Auto Mapper注入到Controller中,然后从控制器中将其在构造函​​数中传递给Repo层。

有可能将其直接注入到Repo中,或者这是我能做的最好的事情?

这是我的启动。ConfigureServices()

public void ConfigureServices(IServiceCollection services)
{
    //** other stuff is here



    // Auto Mapper Configurations
    var mappingConfig = new MapperConfiguration(mc =>
    {
        mc.AddProfile(new MappingProfile());
    });

    IMapper mapper = mappingConfig.CreateMapper();
    services.AddSingleton(mapper);

}     

这里是控制器

[Route("api/[controller]")]
public class EmployeesController : Controller
{ 
    EmployeesRepo _repo;

    public EmployeesController(IMapper mapper)
    {
        _repo = new EmployeesRepo(mapper);
    }

    // GET: Jobs
    [HttpGet("[action]")]
    public IEnumerable<EmployeeDTO> GetAll()
    {
        //** TODO Fix Later hack for debug
        var employees = _repo.GetLast(100);
        return employees;
    }
}

这是一个回购类

public class EmployeesRepo
{
    EFContext db = new EFContext();

    protected readonly IMapper _mapper;

    // Assign the object in the constructor for dependency injection
    public EmployeesRepo(IMapper mapper)
    {
        _mapper = mapper;
    }

    public IEnumerable<EmployeeDTO> GetAllEmployees()
    {
        return db.Employees.ProjectTo<EmployeeDTO>(_mapper.ConfigurationProvider).ToList();
    }

    internal IEnumerable<EmployeeDTO> GetLast(int v)
    {
       return db.Employees.ProjectTo<EmployeeDTO>(_mapper.ConfigurationProvider).ToList();
    }
}

1 个答案:

答案 0 :(得分:2)

让DI框架为您做魔术。

首先注册所有需要注入的内容:

// You can lazily create the IMapper, or if you prefer, use
// a concrete value.
services.AddSingleton<IMapper>(sp => mappingConfig.CreateMapper());

// Make your EmployeesRepo implement IEmployeesRepo
services.AddTransient<IEmployeesRepo, EmployeesRepo>();

// I'm guessing but you'll have the connection string somewhere like this.
// Also using a DbContextPool instead has benefits (though not required)
services.AddDbContextPool<EFContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Data")));

...然后简单地:

IEmployeesRepo _repo;

public EmployeesController(IEmployeesRepo repo)
{
    _repo = repo;
}

...

private readonly EFContext _db;
private readonly IMapper _mapper;

// Assign the object in the constructor for dependency injection
public EmployeesRepo(EFContext db, IMapper mapper)
{
    _db = db;
    _mapper = mapper;
}