如何使用 Microsoft 依赖注入注册 Automapper 5.0?

How to register Automapper 5.0 with Microsoft Dependency Injection?

我正在尝试使用 Microsoft 的内置依赖项注入注册新的 Automapper 5.0:

public static class ServicesContainerConfigure
{
    public static void Configure(IServiceCollection services)
    {
        //This line fails because Mapper has no default constructor
        services.TryAddScoped<IMapper, Mapper>();

        var profileType = typeof(Profile);
        // Get an instance of each Profile in the executing assembly.
        var profiles = Assembly.GetExecutingAssembly().GetTypes()
            .Where(t => profileType.IsAssignableFrom(t)
                        && t.GetConstructor(Type.EmptyTypes) != null)
            .Select(Activator.CreateInstance)
            .Cast<Profile>();

        // Initialize AutoMapper with each instance of the profiles found.
        var config = new MapperConfiguration(cfg =>
        {
            foreach (var profile in profiles)
            {
                cfg.AddProfile(profile);
            }
        });
        config.CreateMapper();
    }
}

Mapper对象中没有默认构造函数。必须有一种方法可以注册它,而无需在映射器 dll 中注册所有注入的对象。

AddXXX 方法通常提供重载,您可以在其中传递 "implementation factory"。似乎 TryAddXXX 没有。如果没有令人信服的理由使用 TryAddXXX 那么这应该适合你:

services.AddScoped<IMapper>(_ =>
{
    var profileType = typeof(Profile);
    // Get an instance of each Profile in the executing assembly.
    var profiles = Assembly.GetExecutingAssembly().GetTypes()
                           .Where(t => profileType.IsAssignableFrom(t) && t.GetConstructor(Type.EmptyTypes) != null)
                           .Select(Activator.CreateInstance)
                           .Cast<Profile>();

    // Initialize AutoMapper with each instance of the profiles found.
    var config = new MapperConfiguration(cfg =>
    {
        foreach (var profile in profiles)
        {
            cfg.AddProfile(profile);
        }
    });

    return config.CreateMapper();
});