在每个Controller类中使用Autofac注入automapper

时间:2016-03-20 19:18:58

标签: asp.net dependency-injection inversion-of-control automapper autofac

我想在应用程序的其他部分注入automapper。我已阅读其他帖子和文章,但我无法弄清楚如何应用它们。我是自动化和IoC的新手。这就是我现在尝试过的。我可以改变什么,以便我将自动控制器注入控制器和其他层?

public class AutomapperConfig
{
    public MapperConfiguration Config { get; set; }
    public void Initialize()
    {
        Config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<CustomerViewModel, CustomerBusinessModel>().ReverseMap();
            ...
        }
}

public static IContainer BuildContainer()
{
    var builder = new ContainerBuilder();
    builder.RegisterControllers(typeof(MvcApplication).Assembly);
    ....
    return builder.Build();
}

public class MvcApplication : System.Web.HttpApplication
{
    public IContainer _container;
    protected void Application_Start()
    {  ...
       _container = AutofacConfig.BuildContainer();
       DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
    }
}

public class CustomersController : Controller
{
    private readonly IBusinessLogic<CustomerBusinessModel> _customerBl;
    private readonly IMapper mapper;

    public CustomersController (IBusinessLogic<CustomerBusinessModel> customer, AutomapperConfig automapper)
    {
        _customerBl= customer;
        mapper = automapper.Config.CreateMapper();
    }
    ...
}

1 个答案:

答案 0 :(得分:1)

试试这个

builder.Register(c => new MapperConfiguration(cfg =>
     {
        cfg.CreateMap<CustomerViewModel, CustomerBusinessModel>().ReverseMap();
        ...
     })
     .AsImplementedInterfaces().SingleInstance();

builder.Register(c => c.Resolve<IConfigurationProvider>().CreateMapper())
    .As<IMapper>();

CustomerController.cs

public class CustomersController : Controller
{
    private readonly IBusinessLogic<CustomerBusinessModel> _customerBl;
    private readonly IMapper _mapper;

    public CustomersController (IBusinessLogic<CustomerBusinessModel> customer, IMapper mapper)
    {
        _customerBl= customer;
        _mapper = mapper;
    }