AutoMapper / AutoMapper.Extensions.Microsoft.DependencyInjection

MIT License
258 stars 79 forks source link

Version 8.1 gives Stackoverflow #148

Closed penfold closed 3 years ago

penfold commented 3 years ago

I've tested my .net core 3.1 branch with the latest versions of AM and AM.Coll. This looks to be working correctly.

I then updated AutoMapper.Extensions.Microsoft.DependencyInjection (from 7.0.0 to 8.1.0) and the SO is now seen.

My usage is:

  services.AddAutoMapper(configurationExpression =>
            {
                configurationExpression.AddCollectionMappers();
            },
            typeof(MapperFactoryExtensions).Assembly);

Originally posted by @penfold in https://github.com/AutoMapper/AutoMapper.Collection/issues/153#issuecomment-727179302

penfold commented 3 years ago

Comparing the 2 release tags (https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/compare/v7.0.0...v8.1.0), it looks like there was some work done on multiple registrations of AutoMapper.

They way we structure our code base means that we are calling the same code above for each feature - therefore there are multiple registrations.

lbargaoanu commented 3 years ago

Maybe call AddCollectionMappers just once?

penfold commented 3 years ago

Testing with an ugly hack, has done the trick. Is it possible to add protection into AM.Collections and AM.Collections.EF?

private readonly static object _syncObject = new object();
        private static bool _areCollectionsMapped = false;

        public static void RegisterDefaultMapper(this IServiceCollection services)
        {
            // Added services needed by type converters
            services.RegisterDatabase();
            services.TryAddSingleton<XXXXX>();
            services.TryAddSingleton<XXXXX>();

            services.AddAutoMapper(configurationExpression =>
            {
                lock (_syncObject)
                {
                    if (!_areCollectionsMapped)
                    {
                        _areCollectionsMapped = true;
                        configurationExpression.AddCollectionMappers();

                        var dbContext = services.BuildServiceProvider().GetService<ApplicationDbContext>();

                        var generatePropertyMaps = new GenerateEntityFrameworkPrimaryKeyPropertyMaps<ApplicationDbContext>(dbContext);

                        configurationExpression.SetGeneratePropertyMaps(generatePropertyMaps);
                    }
                }
            },
            typeof(MapperFactoryExtensions).Assembly);
        }
}
lbargaoanu commented 3 years ago

Perhaps, but someone has to write the code :)

github-actions[bot] commented 3 years ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.