且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在AutoMapper概要文件类中注入服务

更新时间:2023-02-10 08:05:20

要解决您的问题,您只需要在DI中连接IUserManager并确保已解决UserProfile依赖性.

To solve your problem you just need to wire IUserManager in DI, and make sure UserProfile dependency is resolved.

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSingleton<IUserManager, UserManager>();
    services.AddSingleton(provider => new MapperConfiguration(cfg =>
    {
        cfg.AddProfile(new UserProfile(provider.GetService<IUserManager>()));
    }).CreateMapper());
}

话虽如此,我可能会尝试保持每个类的单一职责,并且不将任何服务注入映射配置文件中.您可以改为在映射之前填充对象.这样一来,单元测试也可能会更容易.

And having that said, I would probably try to keep single responsibility per class, and not have any services injected into mapping profiles. You can populate your objects just before the mapping instead. This way it might be easier to unit test as well.