如何将服务从.net core di容器传递到使用automapper创建的新对象 [英] How to pass a service from .net core di container to a new object created with automapper

查看:92
本文介绍了如何将服务从.net core di容器传递到使用automapper创建的新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm facing a scenario where I need to inject a service from asp.net core DI container to the constructor of an object created using automapper.

我不知道这是否是最佳做法,但让我解释一下我要完成的工作.

I don't know if this is the best practice but let me explain what I'm trying to accomplish.

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

I've an asp.net core mvc controller that receives a model parameter, just a POCO, that model needs to be converted into a ViewModel class that contains some business logic, data access etc, in that class object I want to get some info from the injected service, that is the part where I'm having problems, cant figure out how to inject the service from controller to the final ViewModel.

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

My code at this moment looks something like this.

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项目-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项目-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);
        }
    }
}

感谢您的帮助

推荐答案

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

Update the profile to take the configuration as an injected dependency and use ConstructUsing when creating the mapping.

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

这篇关于如何将服务从.net core di容器传递到使用automapper创建的新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆