首页 文章

如何将服务从.net core di容器传递到使用automapper创建的新对象

提问于
浏览
1

我正面临一个场景,我需要从asp.net核心DI容器注入一个服务到使用automapper创建的对象的构造函数 .

我不知道这是不是最好的做法,但让我解释一下我想要完成的事情 .

我有一个asp.net核心mvc控制器,它接收一个模型参数,只是一个POCO,该模型需要转换为一个ViewModel类,其中包含一些业务逻辑,数据访问等,在该类对象中我想得到一些信息从注入的服务,这是我遇到问题的部分,无法弄清楚如何从控制器注入服务到最终的ViewModel .

我此时的代码看起来像这样 .

NewGameModel.cs

namespace MyProject.Shared.Models
{
    public class NewGameModel
    {
        public List<PlayerModel> Players { get; set; }

        public bool IsValid => Players.Any();

        public NewGameModel()
        {
            Players = new List<PlayerModel>();
        }
    }
}

NewGameViewModel.cs

namespace MyProject.Core.ViewModels
{
    public class NewGameViewModel
    {
        private Guid Token = Guid.NewGuid();
        private DateTime DateTimeStarted = DateTime.Now;
        private readonly IConfiguration _configuration;

        public List<PlayerModel> Players { get; set; }

        public NewGameViewModel(IConfiguration config)
        {
            _configuration = config;
        }

        public string DoSomething()
        {
            //Do something using _configuration

            //Business Logic, Data Access etc
        }
    }
}

MapperProfile.cs

namespace MyProject.Service
{
    public class MapperProfile : Profile
    {
        public MapperProfile()
        {
            CreateMap<NewGameModel, NewGameViewModel>();
        }
    }
}

ASP.NET Core project - Startup.cs

namespace MyProject.Service
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSingleton(Configuration);

            var autoMapperConfig = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new MapperProfile());
            });

            var mapper = autoMapperConfig.CreateMapper();

            services.AddSingleton(mapper);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

ASP.NET Core project - GameController.cs

namespace MyProject.Service.Controllers
{
    [Route("api/[controller]")]
    public class GameController : Controller
    {
        private readonly IConfiguration _configuration;
        private readonly IMapper _mapper;

        public GameController(IConfiguration config, IMapper mapper)
        {
            _configuration = config;
            _mapper = mapper;
        }

        [HttpPost]
        public IActionResult CreateNewGame([FromBody]NewGameModel model)
        {
            if (!model.IsValid) return BadRequest();

            //Throws error because no constructor parameter was passed    
            //How to pass the IConfiguration to the destination NewGameViewModel object?

            var viewModel = _mapper.Map<NewGameModel, NewGameViewModel>(model);

            var result = viewModel.DoSomething();

            return CreatedAtRoute("GetGame", new { token = result.GameToken }, result);
        }
    }
}

我将感谢你的帮助

2 回答

  • 0

    更新配置文件以将配置作为注入的依赖项,并在创建映射时使用 ConstructUsing .

    public class MapperProfile : Profile {
        public MapperProfile(IConfiguration config) {
            CreateMap<NewGameModel, NewGameViewModel>()
              .ConstructUsing(_ => new NewGameViewModel(config));
        }
    }
    
  • 1

    对于稍后出现的人,上述方法不是优选的,因为它具有状态内部配置文件 . 相反,使用 AutoMapper.Extensions.Microsoft.DependencyInjection 包并在您的启动内:

    services.AddAutoMapper();
    

    然后在您的配置文件中,告诉AutoMapper您希望使用容器构建目标对象:

    public class MapperProfile : Profile
    {
        public MapperProfile()
        {
            CreateMap<NewGameModel, NewGameViewModel>()
                .ConstructUsingServiceLocator();
        }
    }
    

    然后您的控制器可以依赖于 IMapper ,AutoMapper将使用DI容器来构建视图模型,而您对ASP.NET Core的配置将只是 services.AddAutoMapper(); 的一行

相关问题