[英]How can I Inject Auto Mapper directly in to Repository Layer, below the Controller
这是一个ASP.net Core 2.1项目。
如何将自动映射器直接注入到存储库层? 当前,我已经将Auto Mapper注入到Controller中,然后从控制器中将其在构造函数中传递给Repo层。
可以将其直接注入到Repo中,还是我能做到的最好?
这是我的startup.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();
}
}
让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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.