0

こんにちは、私はユニティを ioc コンテナーとして使用しています。特定のケースでは実装を使用し、残りのケースでは別の実装を使用する必要がある場合があります。

これは私のインターフェースです:

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

そして、これは私の2つの実装です:

 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>();

しかし、コードに到達していないようです.どうすればこの問題を解決できますか?

4

1 に答える 1

1

クラスは次のように定義されます。

AutoMapperGetUpcomingLessonsService 
    : AutoMapperService<GetUpcomingLessons_Result, UpcomingLessonDTO>

そして、次のように登録します。

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

しかし、次のように解決されます。

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

クローズド ジェネリックを登録しているため、型が正確に一致する必要があります。 IEnumerable<GetUpcomingLessons_Result>と同じ型ではありませんGetUpcomingLessons_Result。したがって、 なしで解決するかIEnumerable、クラス定義と登録を に変更する必要がありますIEnumerable<T>

于 2013-06-27T15:35:41.480 に答える