Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapper does not contain a definition for Initialize AutoMapper C#

I have implement Auto Mapper in my asp.net C# project but i got the error:

Mapper does not contain a definition for Initialize

I've tried this example Link Here

I've paste my code:

namespace NewsWeb.Web.Infrastructure
{
    public class AutomapperWebProfile:Profile
    {
        public AutomapperWebProfile()
        {
            CreateMap<DistrictDTO, District>().ReverseMap();
        }

        public static void Run()
        {
            Mapper.Initialize(a =>
            {
                a.AddProfile<AutomapperWebProfile>();
            });
        }
    }
}

In my Golbal.asax.cs file:

 AutomapperWebProfile.Run();

Error image: enter image description here

like image 273
TechGuy Avatar asked Jan 13 '20 08:01

TechGuy


People also ask

What is the use of AutoMapper in C#?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.


1 Answers

Method Mapper.Initialize is obsolete since version v9.0.0 (doc), you need to use MapperConfiguration instead (doc).

var config = new MapperConfiguration(cfg => {
    cfg.AddProfile<AutomapperWebProfile>();
});

var mapper = config.CreateMapper();
// or
var mapper = new Mapper(config);

Initializing a mapper with a static method in a Golbal.asax is not a flexible solution. I would suggest creating a config directly in the custom mapper class.

public interface IFooMapper 
{   
    Foo Map(Bar bar); 
}

public class FooMapper : IFooMapper
{
    private readonly IMapper mapper;

    public FooMapper()
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<FooProfile>();
        });

        mapper = config.CreateMapper();
    }

    public Foo Map(Bar bar) => mapper.Map<Foo>(bar);
}
like image 138
smolchanovsky Avatar answered Oct 06 '22 23:10

smolchanovsky