Search code examples
c#dependency-injectionautomapperblazornullreferenceexception

Automapper Null on Dependency Injection Using [Inject] Attribute


I have a class that fetches some data from a database and I then map the data using AutoMapper. However, for some reason, mapper never gets a value injected so I get a NullReferenceException when I try to use mapper.

public class SearchesEditReview
{
    [Inject]
    public IMapper mapper { get; set; }
        
     public async Task<ViewEvent> GetEditFromId(int id)
     {
        //unrelated code

        return new ViewEvent
                {
                    Data = timelineinfo.FirstOrDefault(),
                    Medias = media,
                    //The below line breaks, saying mapper is null
                    Subjects = mapper.Map<List<DBSubject>, List<ViewSubject>>(subjects)
                };  
     }
}

My relevent Startup.cs looks like:

 public void ConfigureServices(IServiceCollection services)
{
      // Auto Mapper Configurations
      var mapperConfig = new MapperConfiguration(mc =>
      {
           mc.AddProfile(new MappingProfile());
      });

      services.AddHttpContextAccessor();

      IMapper mapper = mapperConfig.CreateMapper();
      services.AddSingleton(mapper);
}

Solution

  • You cannot Inject into a class like that. The syntax your using would work fine on a .razor page however. Please see docs

    Change your class. Note the constructor.

    public class SearchesEditReview
    {
        public SearchesEditReview(IMapper mapper)
        {
            this.mapper = mapper;
        }
           
        IMapper mapper { get; set; }
    
        public async Task<ViewEvent> GetEditFromId(int id)
        {
            //unrelated code
    
            return new ViewEvent
            {
                Data = timelineinfo.FirstOrDefault(),
                Medias = media,
                //The below line breaks, saying mapper is null
                Subjects = mapper.Map<List<DBSubject>, List<ViewSubject>>(subjects)
            };
        }
    }
    
    

    Startup.cs

    ...
    services.AddSingleton(mapper);
    services.AddSingleton<SearchesEditReview>();