I'm trying to inject an instance of ISession
into a custom AutoMapper ValueResolver
.
Here's the resolver
public class ContactTypeResolver
: ValueResolver<Common.Models.ContactType, Models.ContactType>
{
ISession _session;
public ContactTypeResolver(ISession session)
{
_session = session;
}
protected override Models.ContactType ResolveCore(Common.Models.ContactType source)
{
return _session.Load<Models.ContactType>(source.Id);
}
}
I have a profile for setting up AutoMapper
this.CreateMap<Models.PhoneNumber, Common.Models.PhoneNumber>()
.ReverseMap()
.ForMember(d => d.Type, o => o.ResolveUsing<ContactTypeResolver>());
I register the resolver in a StructureMap registry like so
For<ValueResolver<Common.Models.ContactType, Models.ContactType>>()
.Add<ContactTypeResolver>();
I am using session-per-request, and I am set the session inside of a nested container inside of StructureMapDependencyScope.cs
which was created when I added StructureMap to my Web Api project. Here's the code
public void CreateNestedContainer()
{
if (CurrentNestedContainer != null)
{
return;
}
CurrentNestedContainer = Container.GetNestedContainer();
CurrentNestedContainer.Configure(c => c.For<ISession>().Use(ctx => ctx.GetInstance<ISessionFactory>().OpenSession()));
}
And this is how my container is set
var container = StructuremapMvc.StructureMapDependencyScope.Container;
GlobalConfiguration.Configuration.DependencyResolver = new StructureMapWebApiDependencyResolver(container);
container.Configure(x =>
{
x.IncludeRegistry<DefaultRegistry>();
});
Mapper.Initialize(cfg =>
{
cfg.ConstructServicesUsing(container.GetInstance);
foreach (var profile in container.GetAllInstances<Profile>())
cfg.AddProfile(profile);
});
I even tried using the service locator like so
this.CreateMap<Models.PhoneNumber, Common.Models.PhoneNumber>()
.ReverseMap()
.ForMember(d => d.Type, o => o
.ResolveUsing<ContactTypeResolver>()
.ConstructedBy(StructureMap.ObjectFactory.GetInstance<ContactTypeResolver>));
However, when the code runs I get a run-time exception stating
No default Instance is registered and cannot be automatically determined for type 'NHibernate.ISession'.
I also tried injecting another type registered in my container, which also did not work. What am I missing? The session instance does get injected into other objects. Also, other mappings that don't require dependency injection in the same profile work just fine.