Reputation: 181
I want to inject the automapper in other layes of the application. I have read other posts and articles but I can't manage to figure out how to apply them. I am new to automapping and IoC. This is what I've tried by now. What can I change so that I automapper would be injected in controller and other layers?
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();
}
...
}
Upvotes: 0
Views: 556
Reputation: 19600
Try this
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;
}
Upvotes: 1