我有例如以下代码查询DTO列表,并将其映射到视图模型列表。我想让我的容器解析这些视图模型,而不是AutoMapper简单地实例化它们而不进行任何注入。
using (var db = new AppDbContext())
{
var types = await db.ApptTypes
.Where(t => t.BranchId == branchId && (includeDeleted || !t.IsDeleted))
.Include(e => e.CreatedBy)
.Include(e => e.CreatedAt)
.Include(e => e.Org)
.Include(e => e.Branch)
.ToListAsync(cancellationToken);
return Mapper.Map<IEnumerable<ApptTypeDetailViewModel>>(types);
}
答案 0 :(得分:0)
感谢this answer,我找到了一种实现我想要的简洁可靠的方法。主要流程如下:
class Program
{
private static IUnityContainer _container;
static void Main(string[] args)
{
var boot = new Bootstrapper();
boot.Run();
_container = boot.Container;
InitMaps(_container);
var dto = new Dto {Id = 418, Name = "Abrahadabra"};
var model = Mapper.Map<ViewModel>(dto);
}
private static void InitMaps(IUnityContainer container)
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Dto, ViewModel>()
.ConstructUsing(f => UnityObjectFactoty.GetInstance<ViewModel>(container));
});
}
}
工厂:
class UnityObjectFactoty
{
public static TObject GetInstance<TObject>(IUnityContainer container)
{
return container.Resolve<TObject>();
}
}
viewmodel的位置是:
public class ViewModel
{
public ViewModel(IService service)
{
_service = service;
}
private IService _service;
public int Id { get; set; }
public string Name { get; set; }
}
剩下的就是提供容器未解析的ctor参数,但这不是我在这种模式的用例中的要求。