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

时间:2016-07-05 19:55:11

标签: dependency-injection automapper

我正在尝试使用内置的依赖注入注册新的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中注册所有注入的对象。

1 个答案:

答案 0 :(得分:2)

AddXXX方法通常会提供过载,您可以通过&#34;实施工厂&#34;。但似乎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();
});