You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET Framework 4.8中用Simple Injector实现Mapster依赖注入?

Mapster 与 Simple Injector 在 .NET Framework 4.8 MVC/WebApi 中的集成示例

一、Global.asax.cs 配置(Application_Start)

以下是在Application_Start中完成Simple Injector初始化、Mapster注册及映射配置的完整代码:

using System.Web.Mvc;
using SimpleInjector;
using SimpleInjector.Integration.Web.Mvc;
using Mapster;

namespace YourAppNamespace
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            // 1. 初始化Simple Injector容器
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

            // 2. 注册Mapster的IMapper(单例模式,映射规则全局配置一次)
            container.RegisterSingleton<IMapper>(() =>
            {
                var typeAdapterConfig = new TypeAdapterConfig();

                // 示例:添加实体到DTO的映射规则
                typeAdapterConfig.NewConfig<Customer, CustomerDto>()
                      .Map(dest => dest.FullName, src => $"{src.FirstName} {src.LastName}");

                // 可在此添加更多自定义映射规则...

                return new Mapper(typeAdapterConfig);
            });

            // 3. 注册业务服务(示例服务,请求域生命周期)
            container.Register<ICustomerService, CustomerService>(Lifestyle.Scoped);
            // 注册数据访问层依赖(如仓库)
            container.Register<ICustomerRepository, CustomerRepository>(Lifestyle.Scoped);

            // 4. 集成Simple Injector到MVC
            container.RegisterMvcControllers(System.Reflection.Assembly.GetExecutingAssembly());
            container.Verify(); // 验证容器配置有效性

            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }
    }
}

WebApi 适配说明

如果是WebApi项目,将MVC集成代码替换为以下WebApi集成逻辑:

using System.Web.Http;
using SimpleInjector.Integration.WebApi;

// ...其他代码不变...

// 集成到WebApi
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
container.Verify();

GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);

二、业务服务中的Mapster依赖注入示例

定义服务接口与实现类,通过构造函数注入IMapper并使用其完成对象映射:

using System.Collections.Generic;
using System.Linq;
using Mapster;

namespace YourAppNamespace.Services
{
    public interface ICustomerService
    {
        List<CustomerDto> GetAllCustomers();
    }

    public class CustomerService : ICustomerService
    {
        private readonly IMapper _mapper;
        private readonly ICustomerRepository _customerRepo;

        // 构造函数注入依赖
        public CustomerService(IMapper mapper, ICustomerRepository customerRepo)
        {
            _mapper = mapper;
            _customerRepo = customerRepo;
        }

        public List<CustomerDto> GetAllCustomers()
        {
            // 从数据层获取实体
            var customerEntities = _customerRepo.GetAll();
            
            // 使用Mapster映射为DTO列表
            return _mapper.Map<List<CustomerDto>>(customerEntities);
        }
    }
}

三、控制器中的使用示例(MVC)

控制器通过构造函数注入业务服务,间接使用Mapster的映射能力:

using System.Web.Mvc;
using YourAppNamespace.Services;

namespace YourAppNamespace.Controllers
{
    public class CustomerController : Controller
    {
        private readonly ICustomerService _customerService;

        public CustomerController(ICustomerService customerService)
        {
            _customerService = customerService;
        }

        public ActionResult Index()
        {
            var customerDtos = _customerService.GetAllCustomers();
            return View(customerDtos);
        }
    }
}

关键注意事项

  • Mapster的TypeAdapterConfig是线程安全的,全局配置一次即可,因此将IMapper注册为单例是最优选择。
  • Simple Injector的WebRequestLifestyle确保服务实例在单个HTTP请求范围内创建,避免资源泄漏。
  • 容器注册完成后调用container.Verify()可提前发现配置错误,建议保留该步骤。

内容的提问来源于stack exchange,提问作者Roy R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:01:06