Reputation: 5449
Hi I am using unity as my ioc container and I have a case where I need to use an implementation for a specific case and for the rest of the case another implementation.
This is my interface:
public interface IMappingService<TFrom , TTo>
{
TTo Map(TFrom source);
}
And this are my two implementations:
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);
}
}
I acces the implementations in my code using IServiceLocator:
ServiceLocator.GetInstance<IMappingService<IEnumerable<GetUpcomingLessons_Result>, IEnumerable<UpcomingLessonDTO>>>();
In most of the case I would like to use the AutoMapperService implementation and for doing this I specified this in my dependencyConfig file:
container.RegisterType(typeof(IMappingService<,>), typeof(AutoMapperService<,>));
The problem appears when I want to use AutoMapperGetUpcomingLessonsService as my implementation.I tried adding this:
container.RegisterType<IMappingService<GetUpcomingLessons_Result, UpcomingLessonDTO>, AutoMapperGetUpcomingLessonsService>();
But it seems the code is not reached.How can I solve this problem?
Upvotes: 0
Views: 233
Reputation: 22655
Your class is defined as:
AutoMapperGetUpcomingLessonsService
: AutoMapperService<GetUpcomingLessons_Result, UpcomingLessonDTO>
And registered like this:
container.RegisterType<IMappingService<GetUpcomingLessons_Result,
UpcomingLessonDTO>, AutoMapperGetUpcomingLessonsService>();
But is resolved like this:
ServiceLocator.GetInstance<IMappingService<
IEnumerable<GetUpcomingLessons_Result>, IEnumerable<UpcomingLessonDTO>>>();
Since you are registering closed generics the types need to match exactly. IEnumerable<GetUpcomingLessons_Result>
is not the same type as GetUpcomingLessons_Result
. So you should either resolve without the IEnumerable
or change the class definition and registration to be IEnumerable<T>
.
Upvotes: 1