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

时间:2017-09-30 11:29:08

标签: asp.net-core asp.net-core-mvc automapper asp.net-core-webapi asp.net-core-2.0

我正面临一个场景,我需要将一个服务从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核心项目 - 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核心项目 - 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 :(得分:1)

对于后来的人,上述方法不是首选,因为它具有状态内部配置文件。相反,使用data %>% select(state, eunit) %>% filter(eunit == 0) %>% summarise(nrow(.)) %>% group_by(state) 包并在您的启动内:

AutoMapper.Extensions.Microsoft.DependencyInjection

然后在您的个人资料中,告诉AutoMapper您希望使用容器构建目标对象:

services.AddAutoMapper();

然后您的控制器可以依赖于public class MapperProfile : Profile { public MapperProfile() { CreateMap<NewGameModel, NewGameViewModel>() .ConstructUsingServiceLocator(); } } ,AutoMapper将使用DI容器来构建视图模型,而您对ASP.NET Core的配置将只是IMapper的一行

答案 1 :(得分:0)

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

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