Unity为一个接口配置2个实现



嗨,我正在使用unity作为我的ioc容器,我有一个案例,我需要为一个特定案例使用一个实现,而为该案例的其余部分使用另一个实现。

这是我的界面:

public interface IMappingService<TFrom , TTo>
{
    TTo Map(TFrom source);
}

这是我的两个实现:

 public class AutoMapperService<TFrom, TTo> : IMappingService<TFrom, TTo>
{
    public TTo Map(TFrom source)
    {
        TTo target = Mapper.Map<TTo>(source);
        this.AfterMap(source, target);
        return target;
    }
    protected virtual void AfterMap(TFrom source, TTo target)
    {
    }
}
public class AutoMapperGetUpcomingLessonsService : AutoMapperService<GetUpcomingLessons_Result, UpcomingLessonDTO>
    {
        private readonly IOfficialNamesFormatter m_OfficialNamesFormatter;
        public AutoMapperGetUpcomingLessonsService(IOfficialNamesFormatter officialNamesFormatter)
        {
            m_OfficialNamesFormatter = officialNamesFormatter;
        }
        protected override void AfterMap(GetUpcomingLessons_Result source, UpcomingLessonDTO target)
        {
            target.TeacherOfficialName = m_OfficialNamesFormatter.GetOfficialName(target.TeacherGender,
                                                                                  target.TeacherMiddleName,
                                                                                  target.TeacherLastName);
        }
    }

我使用IServiceLocator:访问代码中的实现

ServiceLocator.GetInstance<IMappingService<IEnumerable<GetUpcomingLessons_Result>, IEnumerable<UpcomingLessonDTO>>>();

在大多数情况下,我想使用AutoMapperService实现,为此,我在dependencyConfig文件中指定了这一点:

  container.RegisterType(typeof(IMappingService<,>), typeof(AutoMapperService<,>));

当我想使用AutoMapperGetUpcomingLessonsService作为实现时,问题就会出现。我试着添加这个:

container.RegisterType<IMappingService<GetUpcomingLessons_Result, UpcomingLessonDTO>, AutoMapperGetUpcomingLessonsService>();

但似乎还没有达到密码。我该如何解决这个问题?

您的类定义为:

AutoMapperGetUpcomingLessonsService 
    : AutoMapperService<GetUpcomingLessons_Result, UpcomingLessonDTO>

注册方式如下:

container.RegisterType<IMappingService<GetUpcomingLessons_Result, 
    UpcomingLessonDTO>, AutoMapperGetUpcomingLessonsService>();

但解决方式如下:

ServiceLocator.GetInstance<IMappingService<
    IEnumerable<GetUpcomingLessons_Result>, IEnumerable<UpcomingLessonDTO>>>();

由于您正在注册封闭泛型,因此类型需要完全匹配。CCD_ 1与CCD_ 2不是同一类型。因此,您应该在不使用IEnumerable的情况下进行解析,或者将类定义和注册更改为IEnumerable<T>

最新更新